2013-02-01 17 views
7

我的问题是,我无法确定文件何时成功写入并且文件已关闭。考虑以下情况:如何正确刷新Node.js文件的writeStream?

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

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

回答

7

不要在writeable stream'sclose事件文件的后期处理:

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

而且,不需要在enddestroySoon,他们是one and the same

+0

谢谢,倾听流出“关闭”事件似乎在做伎俩。不知道destroySoon文件是多余的。 –

+0

太好了。很高兴我能帮上忙。 –

+5

这实际上不适合我们。我们仍然有一些情况(在SmartOS/Mac和Windows上,在文件内容被刷新之前发出关闭的情况下) – mgoetzke