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.

1 Answer 1

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
}   
Sign up to request clarification or add additional context in comments.

3 Comments

It worked !! Thanks a lot for such prompt response. you made my day.
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 ?
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.