循环遍历typescript中的文本文件

时间:2017-09-10 10:41:53

标签: javascript typescript typescript-typings typescript2.0

我已阅读本地文件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

用于读取打字稿文件的代码。

 populateFlightList() {
   let data = fs.readFileSync('flight.txt').toString('utf-8'); {
        let textByLine = data.split("\n")
        console.log(textByLine);

    };

现在我想循环并从文件中读取并将数据解析为飞行对象 通过在每次迭代中创建一个新对象并将其添加到arraylist。

   try {
        Scanner fin = new Scanner(file);                
        while(fin.hasNext()) {
          int number = fin.nextInt();                 //flight numer
          String from = fin.next();                   //Departure airport
          String to = fin.next(); //Arrival airport
    }**Code in Java**

我如何在打字稿中这样做?

1 个答案:

答案 0 :(得分:2)

您可以使用readline模块一次读取一行。解析数据仍然是一个手工事件:

import * as fs from 'fs';
import * as rd from '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 from = tokens[1];
    var to = tokens[2]
    console.log(`nr: ${nr} from ${from} to ${to}`);
    data.push({
        number: nr, from, to
    });
})
console.log(`Will be 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} from ${element.from} to ${element.to}`)
    });
})

每一行都会触发一次line事件。在读取整个文件并关闭文件后,close事件将触发,这是整个数据集可用的位置,我们每次构建一个条目,每次line事件发生。

有关readline模块的更多信息,请参阅documentation