我使用child_process.exec
运行npm init
,我可以让它创建package.json,但是创建之后,我的标准输入似乎仍然打开,我想知道当我的子进程结束时,我可能会关闭标准输入,但我不知道它什么时候结束。
这是我的代码:
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);
}
});
完成创建 package.json 后没有触发任何事件,那么完成后如何关闭它?
最佳答案
我遇到了同样的问题,最后以完全不同的方式解决了它。但我假设使用 spawn
而不是 exec
。因为在这个post它假设用于 I/O 进程。
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
如果你仍然想使用 exec
,我已经通过检查 npm init
进程中的最后一个问题,然后触发 process.exit( 0)
写入 block 后。但这并没有让我开心,所以我没有使用它。
关于node.js - 以编程方式使用 Node 子进程执行 'npm init',但无法知道它何时完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28792241/