gpt4 book ai didi

node.js - 在 Node REPL 中以编程方式使用 npm

转载 作者:太空宇宙 更新时间:2023-11-03 22:01:51 25 4
gpt4 key购买 nike

我正在尝试以编程方式使用 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 解释器中运行相同的代码会导致以下错误消息:

$ 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)

两种替代方案都会安装该模块。在 REPL 中运行 npm.commands.install 时是否必须设置任何特殊变量?

编辑:npm (1.3.22)、 Node (v0.10.24)

最佳答案

REPL 上未设置

require.main。如果您从 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 属性(可能还有其他属性)来解析路径等。您可能可以在 REPL session 期间通过设置所有正确的属性来伪造它;您也可以看看 npm CLI source了解如何设置和/或使用此数据。

关于node.js - 在 Node REPL 中以编程方式使用 npm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20817197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com