简体   繁体   中英

NodeJS - convert relative path to absolute

In my File-system my working directory is here:

C:\temp\a\b\c\d

and under b\bb there's file: tmp.txt

C:\temp\a\b\bb\tmp.txt

If I want to go to this file from my working directory, I'll use this path:

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

In case the file is not exist I want to log the full path and tell the user:
"The file C:\temp\a\b\bb\tmp.txt is not exist" .

My question:

I need some function that convert the relative path: "../../bb/tmp.txt" to absolute: "C:\temp\a\b\bb\tmp.txt"

In my code it should be like this:

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

Use path.resolve

try:

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

您还可以将__dirname和__filename用于绝对路径。

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM