节点:如何等待文件完成后再处理?
问题描述:
我的问题是,我不确定何时已成功写入文件且文件已关闭.考虑以下情况:
My Problem is that I can not be sure when a file has been successfully written to and the file has been closed. Consider the following case:
var fs = require('fs');
var outs = fs.createWriteStream('/tmp/file.txt');
var ins = <some input stream>
...
ins.on('data', function(chunk) { out.write(chunk); });
...
ins.on('end', function() {
outs.end();
outs.destroySoon();
fs.stat('/tmp/file.txt', function(err, info) {
// PROBLEM: Here info.size will not match the actual number of bytes.
// However if I wait for a few seconds and then call fs.stat the file has been flushed.
});
});
那么,如何在访问文件之前强制或以其他方式确保已正确刷新文件?我需要确保文件在那里并且完整,因为我的代码必须产生一个外部进程来读取和处理文件.
So, how do I force or otherwise ensure that the file has been properly flushed before accessing it? I need to be sure that the file is there and complete, as my code has to spawn an external process to read and process the file.