您如何 运行 命令说 npm install 或 rake 作为节点 js 应用程序的一部分?

how do you run a commamd say npm install or rake as part of a node js application?

我有一个节点应用程序,我想在其中 运行 命令或任务,例如 npm install 或 rake 或 git clone 。我尝试使用子进程 exec ,但没有 运行ning npm install 任务。有其他方法吗?

如果你想执行 shell(或 cmd,如果你在 Windows)命令,你可以使用 child_process.exec()

https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

这是一个例子:

var exec = require('child_process').exec;
var child;

child = exec("pwd", function (error, stdout, stderr) {
    console.log('stdout: ' + stdout);
    console.log('stderr: ' + stderr);
    if (error !== null) {
        console.log('exec error: ' + error);
    }
});

只需在调用 exec 函数时输入 npm installgit clone 或您想要执行的任何内容,而不是 pwd

您可以执行以下操作 npm install 在节点脚本中工作,

执行npm install npm --save(这需要一些时间)

现在,由于 npm 位于 node_modules 文件夹中,您可以将其导入脚本中。 下面的示例脚本安装 'foobar' 软件包

var npm = require("npm");
npm.load(function (err) {
      npm.commands.install(["foobar"], function (err, data) {
  });
  npm.on("log", function (message) {
    // progress of the npm install
    console.log(message);
  });
});

这只是一个替代方案。按照 Lucian

的建议使用 child_process