NodeJS-将相对路径转换为绝对路径

在我的 abc 中,我的工作目录在这里:

C: 温度 a b c d

在 b bb 下面有个文件 tmp.txt

C: temp a b bb tmp.txt

如果我想从我的工作目录打开这个文件,我会使用下面的路径:

"../../bb/tmp.txt"

如果文件不存在,我想记录完整路径并告诉用户:
“文件 C: temp a b bb tmp.txt 不存在”

我的问题是:

我需要一些 功能改变信仰的相对路径: “ . ./. ./bb/tmp.txt”到绝对值: “ C: temp a b bb tmp.txt”

在我的代码中应该是这样的:

console.log("The file" + convertToAbs("../../bb/tmp.txt") + " is not exist")
105106 次浏览

Use path.resolve

try:

resolve = require('path').resolve
resolve('../../bb/tmp.txt')

You could also use __dirname and __filename for absolute path.

If you can't use require:

const path = {
/**
* @method resolveRelativeFromAbsolute resolves a relative path from an absolute path
* @param {String} relitivePath relative path
* @param {String} absolutePath absolute path
* @param {String} split default?= '/', the path of the filePath to be split wth
* @param {RegExp} replace default?= /[\/|\\]/g, the regex or string to replace the filePath's splits with
* @returns {String} resolved absolutePath
*/
resolveRelativeFromAbsolute(relitivePath, absolutePath, split = '/', replace = /[\/|\\]/g) {
relitivePath = relitivePath.replaceAll(replace, split).split(split);
absolutePath = absolutePath.replaceAll(replace, split).split(split);
const numberOfBacks = relitivePath.filter(file => file === '..').length;
return [...absolutePath.slice(0, -(numberOfBacks + 1)), ...relitivePath.filter(file => file !== '..' && file !== '.')].join(split);
}
};
const newPath = path.resolveRelativeFromAbsolute('C:/help/hi/hello/three', '../../two/one'); //returns 'C:/help/hi/two/one'