在节点的REPL中使用npm进行编程

我试图以编程方式使用npm模块来安装模块。 把下面的代码放到file.js中:

var npm = require('npm'); npm.load({ save : true, loglevel : 'warn' }, function (err) { if (err) return callback(err); npm.commands.install(['async']); }); 

工作得很好:

 $ node file.js async@0.2.9 node_modules/async [ [ 'async@0.2.9', 'node_modules/async', '', undefined, 'async@' ] ] 

但是,在节点解释器中运行相同的代码会导致以下错误消息:

 $ node > var npm = require('npm'); undefined > npm.load({save : true,loglevel : 'warn'},function(err){if (err) return callback(err);npm.commands.install(['async']);}); undefined > /path/node_modules/npm/lib/utils/lifecycle.js:52 env.npm_execpath = require.main.filename ^ TypeError: Cannot read property 'filename' of undefined at /path/node_modules/npm/lib/utils/lifecycle.js:52:36 at /path/node_modules/npm/lib/utils/lifecycle.js:128:12 at Object.oncomplete (fs.js:107:15) 

这两种select安装模块。 当我在REPL中运行npm.commands.install时,是否需要设置任何特殊variables?

编辑:npm(1.3.22),节点(v0.10.24)

require.main没有在REPL上设置。 如果您从Node.js脚本中查看它,它看起来像这样:

 { id: '.', exports: {}, parent: null, filename: '/Users/btilley/test.js', loaded: false, children: [], paths: [ '/Users/btilley/node_modules', '/Users/node_modules', '/node_modules' ] } 

我猜npm使用filename属性(可能还有其他)来解决path等。 您可以在REPL会话期间通过设置所有正确的属性将其伪装出来; 你也可以看一下npm CLI来源 ,看看如何设置和/或使用这些数据。