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!

有帮助吗?

解决方案

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
  }
});
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top