Nidhi Sharma
Nidhi Sharma

Reputation: 471

How to loop over an array and write each iteration to the same file [nodejs]

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

Answers (2)

Jonas Wilms
Jonas Wilms

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

ibrahim mahrir
ibrahim mahrir

Reputation: 31712

Just join the array and write to the file once:

fs.writeFileSync('message.txt', arrayPart.join(""));

Upvotes: 2

Related Questions