如何使用node.js响应命令行提示 [英] How to respond to a command line promt with node.js

查看:220
本文介绍了如何使用node.js响应命令行提示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我如何使用node.js以编程方式响应命令行提示符?例如,如果我执行 process.stdin.write(’sudo ls’); 命令行将提示输入密码。

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?'

另外,我怎么知道什么时候 process.stdin.write('npm install')这样的事件? 完成了吗?

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).

任何帮助都会动摇!

推荐答案

使用 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安装使用 child_process.spawn() 会更好a>可使您在事件退出时附加事件侦听器以运行。您可以执行以下操作:

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

这篇关于如何使用node.js响应命令行提示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆