Cos*_*sta 5 stdin stdout command-line-interface node.js express
如何使用 node.js 以编程方式响应命令行提示?例如,如果我这样做,process.stdin.write('sudo ls');命令行将提示输入密码。是否有“提示”事件?
另外,我怎么知道类似的事情何时process.stdin.write('npm install')完成?
我想用它来进行文件编辑(需要暂存我的应用程序),部署到我的服务器,并反转这些文件编辑(最终部署到生产所需)。
任何帮助都会摇滚!
您需要使用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)
| 归档时间: |
|
| 查看次数: |
5329 次 |
| 最近记录: |