[英]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
. message.txt
将具有arrayPart
的最后一个值。
只需join
数组并一次写入文件即可:
fs.writeFileSync('message.txt', arrayPart.join(""));
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(""));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.