【问题标题】:Resolve relative path relative to another path instead of current working directory解析相对于另一个路径而不是当前工作目录的相对路径
【发布时间】:2019-03-08 00:26:44
【问题描述】:

我有一个如下所示的 Node.js 模块:

module.exports = function()
{
    // linked dependencies
    this.dependency1 = 'dependency1/dependency1.exe';
    this.dependency2 = 'dependency2/dependency2.exe';
    this.dependency3 = 'dependency3/dependency3.exe';
}

我希望开发人员能够轻松地编辑依赖项的位置相对于模块文件本身。但是,在使用模块时,当前工作目录process.cwd() 通常与模块目录不同,因此这些路径无法正确解析。 path.resolve() 似乎只相对于当前工作目录起作用,并且没有任何参数来允许自定义参考点/路径。

我已经能够通过以下方式解决路径,但我觉得它丑陋和繁琐,应该比这更容易:

this.ResolvePath = function(p)
{
    var cwd = process.cwd();
    process.chdir(path.dirname(module.filename));
    var resolvedPath = path.resolve(p);
    process.chdir(cwd);
    return resolvedPath;
}

有没有更清洁的方法来做到这一点?我觉得path.relative() 应该拥有解决方案,但我找不到让它发挥作用的方法。也许将多个path.relative()s 链接在一起可能会起作用,但我现在无法思考它是如何工作的。

【问题讨论】:

    标签: javascript node.js


    【解决方案1】:

    为什么不只是:

     path.resolve(__dirname, p)
    

    __dirnameworks a bit differently and returns the current modules path,然后可以很容易地与相对路径连接。

    【讨论】:

    • 谢谢,我不知道path.resolve() 可以这样使用
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-29
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2011-04-25
    相关资源
    最近更新 更多