Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. 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();
});
like image 649
simo Avatar asked Dec 01 '12 02:12

simo


People also ask

What is child_process spawn?

child_process.exec() : spawns a shell and runs a command within that shell, passing the stdout and stderr to a callback function when complete.

Does child process inherit stdout?

The stdin handle to the child process, if any, will be closed before waiting. This helps avoid deadlock: it ensures that the child does not block waiting for input from the parent, while the parent waits for the child to exit. By default, stdin, stdout and stderr are inherited from the parent.

Can we create child processes in node applications?

Node provides child_process module which provides ways to create child process.

Does spawn support shell syntax?

Shell Syntax and the exec function. By default, the spawn function does not create a shell to execute the command we pass into it. This makes it slightly more efficient than the exec function, which does create a shell.


1 Answers

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); 
})
like image 154
JP Richardson Avatar answered Oct 23 '22 01:10

JP Richardson