使用节点子进程以编程方式执行exec'npm init',但不知道何时完成

Leo*_*Gao 7 child-process node.js

我使用child_process.execrun npm init,我可以让它创建package.json,但是创建后,我的stdin似乎仍然打开,我想知道子进程何时完成,所以我也许关闭了stdin,但是我不知道它何时完成。

这是我的代码:

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);
    }
});
Run Code Online (Sandbox Code Playgroud)

完成创建package.json后,没有任何事件触发,那么如何在完成后将其关闭?

Ada*_*dam 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');
        });
Run Code Online (Sandbox Code Playgroud)