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?'
如何使用node.js以编程方式响应命令行提示符?例如,如果我执行process.stdin.write('sudo ls');命令行将提示输入密码。是否有'提示?'的事件?
Also, how do I know when something like process.stdin.write('npm install')
is complete?
另外,我怎么知道什么时候像process.stdin.write('npm install')完成了?
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 个解决方案
#1
3
You'll want to use child_process.exec()
to do this rather than writing the command to stdin
.
您将需要使用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
}
});
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:
对于npm安装,使用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
}
});
#1
3
You'll want to use child_process.exec()
to do this rather than writing the command to stdin
.
您将需要使用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
}
});
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:
对于npm安装,使用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
}
});