Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js: programmatically setting NODE_PATH

Tags:

node.js

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()?

like image 673
Martin Avatar asked Jan 26 '14 02:01

Martin


2 Answers

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.

like image 141
dwelle Avatar answered Nov 14 '22 13:11

dwelle


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?

like image 1
Trevor Norris Avatar answered Nov 14 '22 13:11

Trevor Norris