写到生成的进程stdin nodejs吗? [英] Write to spawned process stdin nodejs?

查看:59
本文介绍了写到生成的进程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.

实际上上面的代码对我有用。我在子脚本中使用 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;
    }
});

假设

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


推荐答案

您可以使用软件包假设。就像 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/node-suppose

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\n')
.end(function(code){
  console.log('Done: ' + code); 
})

这篇关于写到生成的进程stdin nodejs吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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