gpt4 book ai didi

javascript - 我可以从 Node.js 中运行的 javascript 安装 NPM 包吗?

转载 作者:IT老高 更新时间:2023-10-28 21:49:03 25 4
gpt4 key购买 nike

我可以从 Node.js 中运行的 javascript 文件安装 NPM 包吗?例如,我想要一个脚本,我们称它为“script.js”,它以某种方式(......使用 NPM 或不......)安装通常通过 NPM 提供的包。在这个例子中,我想安装“FFI”。 (npm install ffi)

最佳答案

更新:截至 2021 年 11 月,use of the programmatic API is deprecated .考虑使用 child_process调用 npm CLI。


确实可以以编程方式使用 npm,并且在文档的旧版本中对此进行了概述。它已从官方文档中删除,但仍然存在于源代码控制中,并带有以下声明:

Although npm can be used programmatically, its API is meant for use bythe CLI only, and no guarantees are made regarding its fitness for anyother purpose. If you want to use npm to reliably perform some task,the safest thing to do is to invoke the desired npm command withappropriate arguments.

The semantic version of npm refers to the CLI itself, rather than theunderlying API. The internal API is not guaranteed to remain stableeven when npm's version indicates no breaking changes have been madeaccording to semver.

在原始文档中,以下是提供的代码示例:

var npm = require('npm')
npm.load(myConfigObject, function (er) {
if (er) return handlError(er)
npm.commands.install(['some', 'args'], function (er, data) {
if (er) return commandFailed(er)
// command succeeded, and data might have some info
})
npm.registry.log.on('log', function (message) { ... })
})

由于 npm 存在于 node_modules 文件夹中,您可以像使用任何其他模块一样使用 require('npm') 来加载它。要安装模块,您需要使用 npm.commands.install()

如果您需要查看源代码,那么它也在 GitHub 上。 .这是代码的完整工作示例,相当于在没有任何命令行参数的情况下运行 npm install:

var npm = require('npm');
npm.load(function(err) {
// handle errors

// install module ffi
npm.commands.install(['ffi'], function(er, data) {
// log errors or data
});

npm.on('log', function(message) {
// log installation progress
console.log(message);
});
});

注意 install 函数的第一个参数是一个数组。数组的每个元素都是一个 npm 将尝试安装的模块。

更高级的使用可以在 npm-cli.js 中找到源代码管理文件。

关于javascript - 我可以从 Node.js 中运行的 javascript 安装 NPM 包吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15957529/

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