0

I have a node.js app, which opens a stream:

outputStream = fs.createWriteStream("output.txt");

I then, asynchronously, add text to the file:

outputStream.write( outputTxt, "utf8" );

This code is being run inside a loop, so it happens hundreds of times. However, the loop is asynchronous, so it sometimes pauses, and I can edit the output.txt file in an external editor in the meantime, and (for example) add a few chars in the beginning.

However, when I do that, the next time the outputStream.write is executed, it overwrites the last few chars previously added (the same number of chars that I added externally).

Is there some way to prevent this? Some way to tell the writeStream find the end of the file and then add the text?

Inkbug
  • 1,682
  • 1
  • 10
  • 26
  • I don't know your whole use case, but wouldn't it make sense to append each write to a queue so they're done in order? Completion triggers the callback with processes the next write? You can populate the queue from the loop, but you shouldn't actually write a stream inside of a loop. – Altimus Prime Apr 20 '20 at 19:42
  • @AltimusPrime I am using promises and recursive functions, not an actual loop. – Inkbug Apr 21 '20 at 11:46

0 Answers0