我在 SO 上找到了这个问题,但没有找到任何好的答案。
我使用的是 Node 0.10.40。
我正在使用 child_process.execFile
生成一个子进程,并在该进程中使用 fs.writeFile
执行一些文件 I/O。但是,在执行 fs.writeFile
回调或 filo I/O 完成之前,进程会通过 process.exit(0)
退出。
关于如何延迟进程退出而不setTimeout
的任何想法。我不想使用超时,因为如果我这样做,我还不如使用fs.writeFileSync
。有人找到解决这个问题的方法了吗?
[编辑]
简单地将 process.exit(0)
放入 fs.writeFile 的回调中并不是我在这里寻找的,因为考虑以下场景:
You have a program that spawns child processes. In these child processes, you perform HTTP requests, dump the packet data, perform logic on packet data, then kill process
因此,基本上,当子进程执行唯一操作时,将 process.exit(0)
放入 writeFile
的回调中即可工作这是一个文件 I/O。但从更大的范围来看,如果您确实想在此过程中执行大量逻辑,并时不时地“转储”信息,则这将不起作用。 此进程的“生命周期”不依赖于文件 I/O。它取决于您对数据包数据执行的逻辑。在这种情况下,转储更多的是用于回顾和调试。
最佳答案
您只需确保您调用的是 process.exit();
关于fs.writeFile
的回调,例如:
文件index.js:
var child_process = require('child_process');
child_process.exec('node b.js', function(error, stdout, stderr){
console.log(stdout);
});
文件b.js:
var fs = require('fs');
var count = 0;
function ret(aux){
count++;
if(count==4){
console.log("done i/o operation");
count = 0;
process.exit();
}
}
fs.writeFile('message.txt', 'writing something...', 'utf8', ret);
fs.writeFile('message.txt', 'writing something...', 'utf8', ret);
fs.writeFile('message.txt', 'writing something...', 'utf8', ret);
fs.writeFile('message.txt', 'writing something...', 'utf8', ret);
编辑:
我按照你在评论中询问的方式添加了多个I/O调用,基本上,你可以计算你的回调被调用了多少次,当它达到预定义的值时,你调用 process.exit();
关于Node.js fs.writeFile 在 process.exit(0) 执行之前异步,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37401450/