繁体   English   中英

如何使用“npm”package 以编程方式“npm install”

[英]How to “npm install” programmatically using “npm” package

基本上我想在 package.json 文件中安装所有依赖项。 但是,我想使用 npm 模块以编程方式控制它

我在网上搜索了一些结果,但它们只是显示了如何安装特定的依赖项,而不是 package.json 中的所有依赖项。

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);
  });
});

P/S:请不要建议使用 exec、child-process 或类似的东西。 我处于无法使用 npm cli 的情况

也许您可以要求 package.json 并解析其 object dependencies项。 就像是:

const path = require('path');
const file = path.join(__dirname, 'package.json');
const pkg = require(file);

if (pkg.hasOwnProperty('dependencies')) {
  for (let [key, value] of Object.entries(pkg.dependencies)) {
    const dependency = `${key}@${value}`;

    // Install dependency with npm module
    // ...
  }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM