以编程方式安装提供其版本的NPM包

Ion*_*zău 15 node.js npm

我找到了如何以编程方式安装npm包,代码工作正常:

var npm = require("npm");
npm.load({
    loaded: false
}, function (err) {
  // catch errors
  npm.commands.install(["my", "packages", "to", "install"], function (er, data) {
    // log the error or data
  });
  npm.on("log", function (message) {
    // log the progress of the installation
    console.log(message);
  });
});
Run Code Online (Sandbox Code Playgroud)

如果我想安装第一个版本的hello-world软件包,我怎样才能在NodeJS端使用npm模块执行此操作?

我知道我可以使用子进程,但我想选择npm模块解决方案.

Ion*_*zău 16

NPM NodeJS API没有很好的文档记录,但检查代码会有所帮助.

在这里我们找到以下字符串:

install.usage = "npm install"
              + "\nnpm install <pkg>"
              + "\nnpm install <pkg>@<tag>"
              + "\nnpm install <pkg>@<version>"
              + "\nnpm install <pkg>@<version range>"
              + "\nnpm install <folder>"
              + "\nnpm install <tarball file>"
              + "\nnpm install <tarball url>"
              + "\nnpm install <git:// url>"
              + "\nnpm install <github username>/<github project>"
              + "\n\nCan specify one or more: npm install ./foo.tgz bar@stable /some/folder"
              + "\nIf no argument is supplied and ./npm-shrinkwrap.json is "
              + "\npresent, installs dependencies specified in the shrinkwrap."
              + "\nOtherwise, installs dependencies from ./package.json."
Run Code Online (Sandbox Code Playgroud)

我的问题是关于版本,所以我们可以这样做:hello-world@0.0.1安装0.0.1版本hello-world.

var npm = require("npm");
npm.load({
    loaded: false
}, function (err) {
  // catch errors
  npm.commands.install(["hello-world@0.0.1"], function (er, data) {
    // log the error or data
  });
  npm.on("log", function (message) {
    // log the progress of the installation
    console.log(message);
  });
});
Run Code Online (Sandbox Code Playgroud)

我没有测试,但我确信我们可以使用任何格式的install.usage解决方案.

我写了一个函数来转换dependencies数组中的对象,该数组可以传递给install函数调用.

dependencies:

{
   "hello-world": "0.0.1"
}
Run Code Online (Sandbox Code Playgroud)

该函数获取package.json文件的路径并返回一个字符串数组.

function createNpmDependenciesArray (packageFilePath) {
    var p = require(packageFilePath);
    if (!p.dependencies) return [];

    var deps = [];
    for (var mod in p.dependencies) {
        deps.push(mod + "@" + p.dependencies[mod]);
    }

    return deps;
}
Run Code Online (Sandbox Code Playgroud)

  • 至于 2022 年,这个解决方案不再有效,npm &gt;8.0.0 已弃用编程 API,因此项目内的 `var npm = require("npm");` 不再可能。 (2认同)

Lei*_*iko 8

当我正在为我的工作做这种实现时,我编写了一个简单但高效的nodeJS模块来轻松处理该过程.

npmi的Github存储库

要么

npm install npmi
Run Code Online (Sandbox Code Playgroud)