从当前目录上方加载 node_module

Loading a node_module from above the current directory

我正在构建一个包含多个子应用程序的应用程序。文件结构是这样的:

├── app1
│   ├── app.js
│   ├── node_modules
│   └── package.json
├── shared
│   └── foo.js

app.js 中,我正在这样加载 foo.js

require('../shared/foo');

foo.js 中,我尝试使用 npm 模块 body-parser,如下所示:

var bodyParser = require('body-parser');

Thorws a "cannot find module error" – body-parser 安装在 app1/node_modules 目录中,但是 foo.js 显然在自己的目录中查找并没有找到它。

有没有办法告诉 require() 调用使用调用它的文件的工作目录而不是它自己的目录?或者我是否需要在 /shared 中有第二个 package.json 以允许这种行为?

我最终使用了通过 this Gist:

找到的方法

foo.js 中,我将 require() 调用更改为如下所示:

var bodyParser = require(__base + 'body-parser');

然后在 app.js(加载 foo.js)中,我将其添加到顶部:

global.__base = __dirname + '/node_modules/';

虽然不漂亮,但是很管用。