vitaly-t vitaly-t - 6 months ago 19
Node.js Question

Require for a relative path across modules

I have project

A
that has a
config.json
file in its root. The project has a dependency on external module B, calling
B.setConfig('./config.json')
.

While inside
B.setConfig(path)
, if I call
fs.existsSync(path)
, it says Ok, file exists, but calling
require(path)
fails with
Cannot find module "./config.json"
.

Is it possible to adjust the relative path while inside module
B
to make
require
work?

I would prefer not to call
setConfig
with the full path, as it makes things awkward.

Answer

I found it, eventually, that if we want to take a relative path from module A (call it remotePath), and use it within require in module B, then to get the full path inside module B we can use the following:

var path = require('path');
var fullPath = path.join(path.dirname(process.argv[1]), remotePath);
var moduleInsideA = require(localPath); // this now works

process.argv[1] gives us the module A start-up file, from which we take the directory path, and then join it with the remote relative path, which then gives us the full path.