Exec 'npm init' programmatically with a child process node, but could not know when it will finish

I use child_process.execto run npm init, I can let it create package.json, but after creating my stdin seems open, I want to know when my child process is finished, so I can close stdin, but I did not know when it would end.

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 the events triggered after its completion creates package.json, and how to close it when it finishes?

+4
source share
2 answers

, , -. spawn exec. -.

- , , , child_process.spawn

exec, , npm init, process.exit(0) , . , .

+1

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');
        });
-1

All Articles