附加到路径的正确方式是什么

What is the proper way to append to a path?

本文关键字:方式 是什么 路径      更新时间:2023-09-26

我接受一个目录路径作为其中一个脚本的命令行参数。我想做两件事。第一,我想确认在目录中传递的路径。我想做的第二件事是用子目录名附加到路径上(我提前知道了子目录名)。库中是否有函数会在路径中缺少尾随/字符时自动添加该字符,或者必须手动检查?

例如,如果传递了/User/local,那么我必须将/bin添加到路径,而如果传递了路径/User/local/,则我必须添加bin

谢谢你的帮助。

您似乎只想要path.join、fs.existsSync和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'));

所以如果我运行上面的类似:node test.js /tmp的程序,我会得到:

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

或者我错过了什么?:)

您可以将逻辑放入一个简短的函数中,以确保两个部分之间只有一个"/":

function appendToPath(orig, add) {
    return orig.replace(/'/$/, "") + "/" + add.replace(/^'//, "");
}
var newPath = appendToPath("/User/local", "bin");

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

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

它们都返回"/User/local/bin"