How to respond to a command line promt with node.js

喜你入骨 提交于 2019-12-13 19:16:32

问题


How would I respond to a command line prompt programmatically with node.js? For example, if I do process.stdin.write('sudo ls'); The command line will prompt for a password. Is there an event for 'prompt?'

Also, how do I know when something like process.stdin.write('npm install') is complete?

I'd like to use this to make file edits (needed to stage my app), deploy to my server, and reverse those file edits (needed for eventually deploying to production).

Any help would rock!


回答1:


You'll want to use child_process.exec() to do this rather than writing the command to 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
  }
});

For the npm install one you might be better off with child_process.spawn() which will let you attach an event listener to run when the process exits. You could do the following:

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


来源:https://stackoverflow.com/questions/23209413/how-to-respond-to-a-command-line-promt-with-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!