简体   繁体   English

写入生成的进程stdin 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\n');
});

After I input my data the child script should continue but instead it hang in there. 输入数据后,子脚本应继续,但它会挂在那里。

Solution

Actually the above code work for me. 实际上上面的代码对我有用。 I'm using commander.js in the child script to prompt the user for action. 我在子脚本中使用commander.js来提示用户执行操作。 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;
    }
});

Same thing work with 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();
});

You could use the package suppose . 您可以使用suppose的包。 It's like Unix Expect . 这就像Unix Expect Full disclosure, I'm the author. 完全披露,我是作者。

From the example on the Github page, you can see an example of it scripting NPM: https://github.com/jprichardson/node-suppose 从Github页面上的示例中,您可以看到它编写NPM脚本的示例: https//github.com/jprichardson/node-suppose

Example: 例:

var suppose = require('suppose')
suppose('script')
.on(/\w*/).respond('my data\n')
.end(function(code){
  console.log('Done: ' + code); 
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM