Reputation: 1696
I have a Node.js module that looks like this:
module.exports = function()
{
// linked dependencies
this.dependency1 = 'dependency1/dependency1.exe';
this.dependency2 = 'dependency2/dependency2.exe';
this.dependency3 = 'dependency3/dependency3.exe';
}
I want developers to be able to easily edit the location of the dependencies relative to the module file itself. However, when using the module, the current working directory process.cwd()
is usually not the same as the module directory, so those paths do not resolve correctly. path.resolve()
only seems to work relative to the current working directory, and doesn't have any arguments to allow for a custom reference point/path.
I have been able to resolve the paths in the following way, but I find it ugly and cumbersome, and it should be easier than this:
this.ResolvePath = function(p)
{
var cwd = process.cwd();
process.chdir(path.dirname(module.filename));
var resolvedPath = path.resolve(p);
process.chdir(cwd);
return resolvedPath;
}
Is there a cleaner way to do this? I feel like path.relative()
should hold the solution, but I can't find a way to make it work. Perhaps chaining together multiple path.relative()
s could work, but I can't wrap my brain around how that would work right now.
Upvotes: 3
Views: 5628
Reputation: 138235
why not just:
path.resolve(__dirname, p)
__dirname
works a bit differently and returns the current modules path, which can then be joined easily with the relative path.
Upvotes: 6