Reputation: 1235
I am trying to take values from an array and writing in text file as below code.
while(filedataarr.length>0) {
firstelement = filedataarr.shift();
//console.log(firstelement);
fs.appendFile("D:\\Temp\\testclient.txt", firstelement+"\n", function(err) { if (err) throw err; });
}
It is working actually and i can see data in text file. But the problem is, order of lines is different. when i uncomment the console.log , it works. I think it is happening because of asynchronous calls. I am not getting an idea how to take care of this.
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
please help.
Upvotes: 0
Views: 434
Reputation: 19581
You are executing an sync operation, that you expect to be executed in a sync way.
Since fs.appendFile
is an async operation you can't guarantee that the next line in the file is the last item of the array.
You can try with :
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
}
Upvotes: 5