【发布时间】: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