如何正确地刷新Node.js文件的writeStream?

我的问题是,我不能确定一个文件已经成功写入文件已closures。 考虑以下情况:

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. }); }); 

那么,如何强制或以其他方式确保在访问文件之前文件已被正确刷新? 我需要确保文件存在并完整,因为我的代码必须产生一个外部进程来读取和处理文件。

writeable stream's close事件中执行文件的后处理:

 outs.on('close', function() { <<spawn your process>> }); 

另外, end后不需要destroySoon ,它们是一样的 。

签出https://github.com/TomFrost/FlushWritable – 我不知道为什么它没有写入到可写内核,但这应该做的伎俩。

另外,在GitHub https://github.com/nodejs/node-v0.x-archive/issues/7348上有一个讨论&#x3002;