Martin
Martin

Reputation: 3602

Node.js: programmatically setting NODE_PATH

I would like to load files dynamically in Node.js and this poses a problem that Node looks in node_modules of the calling modules instead of looking in the node_modules of file being loaded.

The reason I do not want to use require() is because these are plugins and they can be included in the main app by simply being concatenating. So using require() breaks the plugins. They have to be loaded directly into the main app context, but they have to have access to their local node_modules as well.

I use vm.runInNewContext() to evaluate the code. But how do I pass NODE_PATH to runInNewContext()?

Upvotes: 16

Views: 10127

Answers (2)

dwelle
dwelle

Reputation: 7294

To set NODE_PATH programmatically, you can run this magic on top of your root node file (source):

process.env.NODE_PATH = "your/path";
require("module").Module._initPaths();

But keep your eyes peeled when you upgrade your node lest they change how it works.

Upvotes: 36

Trevor Norris
Trevor Norris

Reputation: 21109

Since vm.runInNewContext() has no knowledge about your current context, nor is it given its own new "global" context, I assume the following would work:

var sb = { process: { env: { NODE_PATH: '/my/path/' }}};
vm.runInNewContext('process.env', sb);
// return: { NODE_PATH: '/my/path/' }

Unless I'm missing something. If I am could you explain in more detail?

Upvotes: 1

Related Questions