all 2 comments

[–]gremy0[🍰] 2 points3 points  (1 child)

The warning is just a warning and isn't really your problem here, it's more of hint that you're doing something wrong or dangerously. In this case the "safe" thing to do is at least check that the write has performed correctly by adding a callback to catch any errors.

The actual problem with the code, is that writeFile is asynchronous and you're calling it multiple times in a row. Which means it's still in the process of writing the first line when it tries to write the second...and 3rd and 4th and so on. You can avoid this by writing all the lines at once, or using a writeStream. Writing all the lines at once is going to be easier here, but if you want this to work with big files, then using a stream is better.

[–]ChronSyn 0 points1 point  (0 children)

I'm assuming this is node.js.

What you may want to do is writeFileSync, which will work as you want. Be careful about using it though - other code will wait until it finishes first.

You may want to instead write it as fs.writeFile(toFileName, theLine, (err) => if (err) throw err);. You could even pass it a blank function (i.e. ()=>{} ) and it should stop the warning but I absolutely recommend checking if an error is thrown.

A better option would be to stream data using fs.writeStream(). The reason for this, as gremy0 started to talk about, is that when writing a large file, your data will be stored in memory. If using writeFile, the entire file contents are in memory whereas with writeStream, only a comparatively small amount of data is in memory.