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

113

在我的文件系统中,我的工作目录在这里:

C:\temp\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")
4个回答

233

使用path.resolve

尝试:

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

23
你也可以使用 const {resolve} = require("path"); - harveyhans
@DarkKnight,有没有避免使用../../../etc的方法? - Code_Crash
1
@Code_Crash 你可以像这样使用变量或更改工作目录:https://dev59.com/X2Ij5IYBdhLWcg3w4Ivt。使用变量比更改工作目录更可取,因为更改工作目录可能会导致不必要的副作用。 - DarkKnight
使用更新的 esm,可以这样写:import path from 'path',然后调用 path.resolve() - Timo

15

你也可以使用 __dirname 和 __filename 来获取绝对路径。


8
仅使用此功能可了解文件所在的当前目录和当前文件的绝对路径。 - kryptokinght

1

如果你无法使用 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'

谢谢,这实际上非常有效 :-) - undefined

-1

你可以通过在 package.json 文件中添加以下内容轻松实现:

"imports": {
    "#library/*": "./library/*"
}

在每个文件中,您可以使用以下语法导入库:

const db = require('#library/db.js');

你的集成开发环境(IDE)将自动检测文件和db.js模块中可用的函数。

==================================

如果您需要在目录内管理单独的软件包(每个软件包都有单独的package.json文件),那么您的问题就完全不同了:
您需要使用工作区来管理您的软件包,以便在monorepo中进行管理。有关工作区的完整指南,请参阅官方文档:

https://docs.npmjs.com/cli/v7/using-npm/workspaces/


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接