写入生成的进程标准输入 nodejs? [英] Write to spawned process stdin nodejs?
问题描述
我有一个脚本要从另一个脚本运行.问题是子脚本(进程)在继续之前需要用户输入.
I have a script that I want to run from another one. The problem is that the child script (process) needs an user input before it continues.
var child = spawn('script');
child.stdin.setEncoding('utf8');
child.stdout.on('data', function (data) {
console.log(data.toString().trim()); // tells me to input my data
child.stdin.write('my data
');
});
在我输入数据后,子脚本应该继续,但它会挂在那里.
After I input my data the child script should continue but instead it hang in there.
实际上上面的代码对我有用.我在子脚本中使用 commander.js 来提示用户采取行动.以下是我如何回应孩子的脚本提示:
Actually the above code work for me. I'm using commander.js in the child script to prompt the user for action. Here is how I respond to a child's script prompt:
child.stdout.on('data', function (data) {
switch (data.toString().trim()) {
case 'Username:':
child.stdin.write('user');
break;
case 'Password:':
child.stdin.write('pass');
break;
}
});
与 suppose 相同:
var suppose = require('suppose');
suppose('script')
.on('Username: ').respond('user')
.on('Password: ').respond('pass')
.error(function (err) {
console.log(err.message);
})
.end(function (code) {
console.log(code);
done();
});
推荐答案
您可以使用 suppose
包.这就像 Unix Expect.完全公开,我是作者.
You could use the package suppose
. It's like Unix Expect. Full disclosure, I'm the author.
从 Github 页面上的示例,您可以看到它编写 NPM 脚本的示例:https://github.com/jprichardson/节点假设
From the example on the Github page, you can see an example of it scripting NPM: https://github.com/jprichardson/node-suppose
示例:
var suppose = require('suppose')
suppose('script')
.on(/w*/).respond('my data
')
.end(function(code){
console.log('Done: ' + code);
})
这篇关于写入生成的进程标准输入 nodejs?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!