简体   繁体   English

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

[英]NodeJS - convert relative path to absolute

In my File-system my working directory is here:在我的文件系统中,我的工作目录在这里:

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

and under b\bb there's file: tmp.txt在 b\bb 下有文件:tmp.txt

C:\temp\a\b\bb\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:如果我想从我的工作目录 go 到这个文件,我将使用这个路径:

"../../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" . “文件 C:\temp\a\b\bb\tmp.txt 不存在”

My question:我的问题:

I need some function that convert the relative path: "../../bb/tmp.txt" to absolute: "C:\temp\a\b\bb\tmp.txt"我需要一些function相对路径:“../../bb/tmp.txt”转换为绝对路径:“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 使用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'

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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