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()
?
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With