我一直试图找到一种在使用Node.js时写入文件的方法,但没有成功.我怎样才能做到这一点?
我的问题是我无法确定何时成功写入文件并且文件已关闭.考虑以下情况:
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.
});
});
Run Code Online (Sandbox Code Playgroud)
那么,在访问文件之前,如何强制或以其他方式确保文件已正确刷新?我需要确保文件存在并完成,因为我的代码必须生成一个外部进程来读取和处理文件.