16

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. 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();
});
Community
  • 1
  • 1
simo
  • 15,078
  • 7
  • 45
  • 59
  • Just a thought: do you need to end `stdin` in order for your script to respond? See also: http://nodejs.org/api/stream.html#stream_stream_end – skeggse Dec 01 '12 at 06:46
  • From the docs: Closing this stream via end() often causes the child process to terminate. - http://nodejs.org/api/child_process.html#child_process_child_stdin And it does terminate the child process I can confirm it. – simo Dec 01 '12 at 07:59

1 Answers1

11

You could use the package suppose. It's like 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

Example:

var suppose = require('suppose')
suppose('script')
.on(/\w*/).respond('my data\n')
.end(function(code){
  console.log('Done: ' + code); 
})
JP Richardson
  • 38,609
  • 36
  • 119
  • 151
  • There seems to be some problem with my child script because it doesn't work with *suppose* either. I'm using *commander.js* in my child script to prompt the user for action. Maybe this is the problem in some way .. – simo Dec 01 '12 at 08:40
  • I was missing one trailing white space character in the first prompt but I guess this is something specific to *commander.js*. Anyway your module work for me so I'll mark your answer. – simo Dec 01 '12 at 09:37