use*_*sam 0 javascript node.js
我正在尝试从数组中获取值并按以下代码写入文本文件。
while(filedataarr.length>0) {
firstelement = filedataarr.shift();
//console.log(firstelement);
fs.appendFile("D:\\Temp\\testclient.txt", firstelement+"\n", function(err) { if (err) throw err; });
}
Run Code Online (Sandbox Code Playgroud)
它实际上正在工作,我可以在文本文件中看到数据。但问题是,行的顺序是不同的。当我取消注释 console.log 时,它可以工作。我认为这是由于异步调用而发生的。我不知道如何处理这个问题。
Data Comparison
Array Data File Data
11:41:24:562,9057 11:41:24:562,9057
11:41:24:567,1025 11:41:24:569,8872
11:41:24:569,8872 11:41:24:567,1025
11:41:24:571,1572 11:41:24:571,1572
11:41:24:573,429 11:41:24:573,429
11:41:24:574,61 11:41:24:577,3683
11:41:24:576,4863 11:41:24:574,61
11:41:24:577,3683 11:41:24:576,4863
11:41:24:578,8483 11:41:24:578,8483
17:11:53:826,1757 17:11:53:826,1757
Run Code Online (Sandbox Code Playgroud)
请帮忙。
您正在执行同步操作,您希望以同步方式执行该操作。
由于fs.appendFile是异步操作,您不能保证文件中的下一行是数组的最后一项。
您可以尝试:
while(filedataarr.length>0) {
firstelement = filedataarr.shift();
fs.appendFileSync("D:\\Temp\\testclient.txt", firstelement+"\n" );
// ^ sync will stop the execution of the loop until the operation
// is finished
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
297 次 |
| 最近记录: |