Reputation: 471
I have an array of data which i want to loop over and while looping over I want to write them to the same file. How i can achieve the same, my following code will only print the last iteration.
for (j = 0; j < arrayPart.length; j++){
fs.writeFileSync('message.txt', arrayPart[j])
}
message.txt
will have the last value of arrayPart
.
Upvotes: 6
Views: 4810
Reputation: 138557
Instead of opening/writing/closing at every iteration I would open a write stream, write inside the loop and close at the end:
const message = fs.createWriteStream(__dirname + "./message.txt");
for (let j = 0; j <arrayPart.length; j++){
message.write(arrayPart[j]);
}
message.close();
Or you just join the array and write all at once:
fs.writeFileSync('message.txt', arrayPart.join(""));
Upvotes: 4
Reputation: 31712
Just join
the array and write to the file once:
fs.writeFileSync('message.txt', arrayPart.join(""));
Upvotes: 2