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
.
-
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
2 Answers
Reset to default 4Instead 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条)