javascript - Looping through the text file in typescript -
i have read local file flight.txt
1 dfw bom 2016-05-20 12:20 2016-05-21 02:40 1084.00 jetairways 100 2 dfw del 2016-04-24 17:15 2016-04-25 07:20 1234.00 lufthansa 100 3 dfw fra 2016-06-05 13:30 2016-06-05 03:32 674.00 americanairlines 100
code used read file in typescript.
populateflightlist() { let data = fs.readfilesync('flight.txt').tostring('utf-8'); { let textbyline = data.split("\n") console.log(textbyline); };
now want loop , read file , parse data flight objects creating new object in each iteration , adding arraylist.
try { scanner fin = new scanner(file); while(fin.hasnext()) { int number = fin.nextint(); //flight numer string = fin.next(); //departure airport string = fin.next(); //arrival airport }**code in java**
how do in typescript?
you can use readline
module read 1 line @ time. parsing data still manual affair:
import * fs 'fs'; import * rd 'readline' var reader = rd.createinterface(fs.createreadstream("w:\\tmp\\stack\\2\\data.txt")) var data: array<{ number: number; from: string; to: string}> = []; reader.on("line", (l: string) => { var tokens = l.split(' '); var nr= parseint(tokens[0]); var = tokens[1]; var = tokens[2] console.log(`nr: ${nr} ${from} ${to}`); data.push({ number: nr, from, }); }) console.log(`will empty data has not yet been read ${data.length}` ); reader.on("close", ()=> { console.log(`data has been read ${data.length}` ); data.foreach(element => { console.log(`nr: ${element.number} ${element.from} ${element.to}`) }); })
the line
event triggered once each line. close
event trigger after entire file has been read , file closed, entire data set available, build 1 entry @ time, each time line
event occurs.
for more readline module consult documentation
Comments
Post a Comment