如何用Node.js的命令行PROMT响应(How to respond to a command

2019-10-19 23:29发布

如何将我的命令行进行响应的node.js编程提示? 例如,如果我process.stdin.write('sudo ls'); 命令行会提示输入密码。 是否有一个事件“提示?

此外,我怎么知道什么时候像process.stdin.write('npm install')是否已经完成?

我想用这个来使文件编辑(阶段性我的应用程序需要),部署到我的服务器,并扭转这些文件的修改(需要最终部署到生产)。

任何帮助将摇滚!

Answer 1:

你要使用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
  }
});

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


文章来源: How to respond to a command line promt with node.js