2

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.

chazsolo
  • 7,873
  • 1
  • 20
  • 44
V. Rubinetti
  • 1,324
  • 13
  • 21

1 Answers1

5

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.

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • Thank you, I was unaware that `path.resolve()` could be used in that manner – V. Rubinetti Oct 02 '18 at 20:26
  • For people wanting to use `require.resolve` (for its automatic adding/finding of `.js`, `/index.js`, etc.), but just from a different folder than the current file's, see [here](https://nodejs.org/api/modules.html#requireresolverequest-options). Example: `let resolvedPath = require.resolve(subPath, {paths: [pathToResolveSubPathFrom]});` – Venryx Mar 10 '22 at 05:10