How to clean Node.js file writeStream?

My problem is that I cannot be sure when the file was successfully written and the file was 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 can I make or otherwise make sure that the file has been cleaned correctly before accessing it? I must be sure that the file is there and is complete, since my code must spawn an external process for reading and processing the file.

+7
source share
2 answers

Do your post-processing of the file in the writeable stream's close event:

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

In addition, there is no need to destroySoon after end , they are one and the same .

+7
source

Check out https://github.com/TomFrost/FlushWritable - I don't know why it is not written in the Writable core, but this should do the trick.

This is also discussed on GitHub https://github.com/nodejs/node-v0.x-archive/issues/7348 .

0
source

All Articles