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

2

7

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?

Nestle answered 1/3, 2015 at 10:1 Comment(0)
M
2

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.

Mikes answered 31/5, 2017 at 6:40 Comment(0)
E
0

https://nodejs.org/api/child_process.html#child_process_child_process_exec_command_options_callback

const exec = require('child_process').exec;
exec('npm test', (err, stdout) => {
          console.log(stdout);
          console.log('over');
        });
Eulaliaeulaliah answered 27/4, 2017 at 9:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.