Node.js: programmatically setting NODE_PATH
Asked Answered
B

2

15

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

Bergwall answered 26/1, 2014 at 2:42 Comment(0)
S
35

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.

Samaveda answered 28/11, 2015 at 21:26 Comment(3)
If anyone's trying to use NODE_PATH and it's not working, make sure you have this second line with the _initPaths() call.Cellule
Thank you @dwelle, it works for me! One note is that you just need to put the code before you require the module which needs a special NODE_PATH.Fremitus
Thanks, using the second line with dotenv fixes my problemSteading
D
1

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?

Darrel answered 26/1, 2014 at 7:52 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.