0

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.

usersam
  • 1,125
  • 4
  • 27
  • 54

1 Answers1

5

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
}   
drinchev
  • 19,201
  • 4
  • 67
  • 93
  • It worked !! Thanks a lot for such prompt response. you made my day. – usersam Oct 06 '17 at 13:44
  • One ques. I am writing to file just to compare at source and destination , just for testing. In actual, i want to send this data to client through socket. like, io.emit('currtime', { currtime: firstelement.split(',')[0], number: firstelement.split(',')[1]}) . will it be sync ? – usersam Oct 06 '17 at 13:46
  • Not really. All operations, regarding network, filesystem are sync by default. Assuming you are using `socket.io` the elements that you [send should be received in the same order](https://stackoverflow.com/questions/9282892/websocket-are-server-data-sent-synchronously). – drinchev Oct 06 '17 at 13:53