解决相对于其他路径而不是当前工作目录的相对路径

时间:2018-10-02 20:14:36

标签: javascript node.js

我有一个看起来像这样的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()链接在一起是可行的,但我无法为现在的工作方式着迷。

1 个答案:

答案 0 :(得分:3)

为什么不只是:

 path.resolve(__dirname, p)

__dirname works a bit differently and returns the current modules path,然后可以轻松将其与相对路径结合起来。