如何使用 Node.js 响应命令行提示

Cos*_*sta 5 stdin stdout command-line-interface node.js express

如何使用 node.js 以编程方式响应命令行提示?例如,如果我这样做,process.stdin.write('sudo ls');命令行将提示输入密码。是否有“提示”事件?

另外,我怎么知道类似的事情何时process.stdin.write('npm install')完成?

我想用它来进行文件编辑(需要暂存我的应用程序),部署到我的服务器,并反转这些文件编辑(最终部署到生产所需)。

任何帮助都会摇滚!

jsh*_*ley 2

您需要使用child_process.exec()来执行此操作,而不是将命令写入stdin.

var sys = require('sys'),
    exec = require('child_process').exec;

// execute the 'sudo ls' command with a callback function
exec('sudo ls', function(error, stdout, stderr){
  if (!error) {
    // print the output
    sys.puts(stdout);
  } else {
    // handle error
  }
});
Run Code Online (Sandbox Code Playgroud)

对于一个npm install你可能会更好的人来说,child_process.spawn()它可以让你附加一个事件侦听器以在进程退出时运行。您可以执行以下操作:

var spawn = require('child_process').spawn;

// run 'npm' command with argument 'install'
//   storing the process in variable npmInstall
var npmInstall = spawn('npm', ['install'], {
  cwd: process.cwd(),
  stdio: 'inherit'
});

// listen for the 'exit' event
//   which fires when the process exits
npmInstall.on('exit', function(code, signal) {
  if (code === 0) {
    // process completed successfully
  } else {
    // handle error
  }
});
Run Code Online (Sandbox Code Playgroud)

  • 是的,这并没有清楚地解释实际的响应写作是如何发生的。另外,如果我需要执行多轮提示和响应(即请求用户名,然后请求密码)怎么办?它会是一组嵌套的“execs”,还是会产生一个新进程? (7认同)
  • 这会打印输出,但是它将如何传递密码呢? (4认同)