简体   繁体   English

如何遍历数组并将每个迭代写入同一文件[nodejs]

[英]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.

相关问题 循环nodejs的每次迭代延迟 - Delay in each iteration of loop nodejs 如何在for循环中等待每次迭代并在NodeJS中将响应作为API响应返回 - How to wait for each iteration in for loop and return response as API response in nodeJS 在 for 循环的每次迭代中输出一个数组 - Outputting an array each iteration of a for loop 如何在 javascript 中的 for 循环的每次迭代中将一个数组插入另一个数组 - How to insert an array to another array at each iteration of a for loop in javascript jquery / javascript-如何遍历数组并在每次迭代中创建变量? - jquery/javascript -how to loop through array and create variables in each iteration? 如何将for循环的每次迭代结果存储到数组中(Javascript) - How to store the result of each iteration of a for loop into an array (Javascript) 循环遍历数组以尝试页面上的多个选项,并在每次迭代时返回到初始页面 - Loop over an array to try multiple options on a page and come back to that initial page for each iteration CasperJS for loop每次迭代都会产生相同的结果 - CasperJS for loop produces the same result for each iteration 如何使用nodejs将数组obj写入文件 - how to write array obj into file with nodejs 每次循环迭代时更改数组元素的顺序 - change order of array elements each loop iteration
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM