how to join strings at given positions in path modules

Posted June 2, 2021 278 views

Write a Javascript program that contains a function that takes three parameters: pathToFile, a string to indicate position, a string to append respectively.

Your task is to return an object through the function which contains three properties :

  • 1st property named: baseName: which contains the basename of the file.
  • 2nd property named: dirName : which contains the directory name of the file.
  • 3rd property named: finalPath : which joins the given string at given positions.

Given positions can be :

  • ‘start’: to join the given string at the starting of the path.
  • 'end’: to join the given string at the end of the path.

Suppose if the filepath is “/home/company/job” and position is “start” and data is “myComputer” i need the output as “myComputer/home/company/job”

and this is what i did in code:

const path = require('path');

function pathfunc(pathToFile,pos1,pos2){
    let dir_name = path.dirname(pathToFile);
    let base_name = path.basename(pathToFile);
    let join_path = path.join(pos1,base_name,dir_name,pos2);
    let object = {
        baseName : base_name,
        dirName : dir_name,
        finalPath : join_path,
    return object;

module.exports = pathfunc;
Submit an answer

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!