What is the proper way to append to a path?

I am accepting a path to a directory as a command line argument to one of my scripts. There are two things I want to do. The first is that I want to confirm that path passed in a directory. The second thing I want to do is append to the path with sub-directory names (I know the sub-directory names ahead of time). Are there any functions in the library that will automatically add a trailing / character to the path if it is missing, or must I check for this manually?

For instance, if /User/local is passed, then I must add /bin to the path, whereas I must add bin if the path /User/local/ is passed.

Thanks for the help.

It seems like you just want path.join, fs.existsSync, and fs.statSync

var path = require('path');
var fs = require('fs');

var dir = process.argv[2];

console.log(dir);
console.log(fs.existsSync(dir) && fs.statSync(dir).isDirectory());
console.log(path.join(dir, 'mysubdir'));

So if I run the above like: node test.js /tmp I will get:

/tmp
true
/tmp/mysubdir

var tail = 'bin/test/',
    path = arg[arg.length-1] === '/' ? arg + tail : arg + '/' + tail;

Or I missing something? :)

You can put the logic into a short function that makes sure there is one and only one "/" between the two parts:

function appendToPath(orig, add) {
    return orig.replace(/\/$/, "") + "/" + add.replace(/^\//, "");
}

var newPath = appendToPath("/User/local", "bin");

or

var newPath = appendToPath("/User/local/", "/bin");

or

var newPath = appendToPath("/User/local", "/bin");

They all return "/User/local/bin".