简体   繁体   中英

node.js writing array value to text file

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.

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
}   

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM