I am using Node's fs.WriteStream to write data into files. I am looping through an array of objects and writing each object with the write() function.
The problem is that I would like to know once this loop is over and all the write() calls are done, but I cannot make it work.
I've attempted a few solutions, such as not using a stream, but that would create other problems. The solution I last attempted was checking in the loop if it was the last item, and if so, closing, ending or destroying the stream.
None of these worked. The event is emmited before the file is actually written.
Here follows my code, and I appreciate any help I can get. Thank you very much.
async function writeFile(path, data) {
try {
const writeStream = fs.createWriteStream(path, {
flags: "w"
})
data.forEach((file, index) => {
writeStream.write(`${file.name}\n`, (err) => {
if(err) throw err
if(index === (data.length - 1)) writeStream.end(); //I attempted close() and destroy() too, none worked
})
})
writeStream.on("finish", () => {
console.log("All files were written.") //Currently being emmited before all is written.
})
} catch (err) {
throw (err)
}
}