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

I have an array of data which i want to loop over and while looping over I want to write them to the sa

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.

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.

Share Improve this question edited Oct 15, 2018 at 20:57 ibrahim mahrir 31.7k5 gold badges49 silver badges77 bronze badges asked Oct 15, 2018 at 20:53 Nidhi SharmaNidhi Sharma 4711 gold badge5 silver badges18 bronze badges 1
  • writeFile overwrites the file every time you call it. See the docs, specifically "writes data to a file, replacing the file if it already exists." – Heretic Monkey Commented Oct 15, 2018 at 20:56
Add a ment  | 

2 Answers 2

Reset to default 4

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(""));

Just join the array and write to the file once:

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744220941a4563776.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信