Node.js:以编程方式设置 NODE_PATH

问题描述:

我想在 Node.js 中动态加载文件,这带来了一个问题,即 Node 在调用模块的 node_modules 中查找,而不是在文件的 node_modules 中查找正在加载.

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.

我不想使用 require() 的原因是因为这些是插件,它们可以通过简单地连接来包含在主应用程序中.所以使用 require() 会破坏插件.它们必须直接加载到主应用程序上下文中,但它们也必须能够访问其本地 node_modules.

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.

我使用 vm.runInNewContext() 来评估代码.但是如何将 NODE_PATH 传递给 runInNewContext()?

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

要以编程方式设置 NODE_PATH,您可以在根节点文件 (来源):

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.