I want to append lines to a file, which is a writeable stream, in Node, in a specific order, through a loop.
Here is a simplified version of what I am talking about:
var fs = require('fs');
var outfile = fs.createWriteStream('outfile.txt');
for (var i = 0; i < 200; i++) {
outfile.write('i', function (err, len) {
console.log('written');
});
}
I need the file to be written sequentially meaning that it would write, 12345...etc
in order. My understanding is that outfile.write
is async, meaning that it is possible for the file to be written out of order - is this correct?
I see from the node docs
Note that it is unsafe to use fs.write multiple times on the same file without waiting for the callback. For this scenario, fs.createWriteStream is strongly recommended.
So I believe that using a stream is best, however, I am not sure hot to guarantee that the data chunk was written succesfully before moving on to the next iteration in the loop. How should I go about doing that? Thanks.