Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

exec 'npm init' programmatically with node child process, but could not know when it finished

I use child_process.exec to run npm init, I can let it create package.json, but after creating, my stdin seems still open, I want to know when my child process finished so I maybe close the stdin, but I could not know when it finished.

Here is my code:

var child = exec('npm init', function (err, stdout, stderr) {

    console.log('over');
});
child.stdout.on('data', function(data) {

    process.stdout.write(data);

    //process.stdin.resume();
});
child.stdout.on('end', function() {
    console.log('end out');
});
child.stdout.on('close', function() {
    console.log('close out');
});
child.on('exit', function() {
    console.log('exit');
});
child.on('close', function() {
    console.log('close');
});
child.on('disconnect', function() {
    console.log('disconnect');
});

// read stdin and send to child process
process.stdin.on('readable', function() {

    var chunk = process.stdin.read();

    if(chunk !== null) {
        child.stdin.write(chunk);
    }
});

None of events fired after it finishing create package.json, so how to close it when it finished?

like image 790
Leo Gao Avatar asked Mar 01 '15 10:03

Leo Gao


1 Answers

I run into the same issue and finally solved it in a completely different way. But I would assume to use spawn instead of exec. Because in this post it is assumes for I/O processes.

If you need to use handle process I/O with streams, such as when you are expecting large amounts of output, use child_process.spawn

If you still want to use exec, I have solved it by checking for the last question in npm init process, and then firing process.exit(0) after the chunk has been written. But this didn't made me happy, so I haven't used it.

like image 68
DoomyTheFroomy Avatar answered Nov 15 '22 10:11

DoomyTheFroomy