Node js中的语句顺序

时间:2015-11-12 15:44:13

标签: node.js

Node JS的新手,仍然习惯了事情的完成方式。 我正在处理具有以下结构的文件:

[1447113604] [104] [86]
[1447113605] [111] [91]
[1447113606] [127] [114]
[1447113607] [115] [105]
[1447113608] [120] [101]
[1447113609] [105] [100]
[1447113610] [89] [88]

我逐行读取它,解析每一行并创建具有3个属性的对象(timestamp,count1,count2),然后我将新创建的对象添加到数组中,最后我想循环遍历数组并使用for循环打印其元素。

var readline = require('readline');
var fs = require('fs');

var arr_counters = [];

var rl = readline.createInterface({        
      input : fs.createReadStream("cps.log"),
      output: process.stdout,
      terminal: false    
})

rl.on('line',function(line){
    console.log(line) //or parse line
    var tokens = line.split(" ");

  var str_TS = tokens[0].substring(1,11);   //strip '[' ']'
  var int_p = tokens[1].substring(1, tokens[1].length - 1); //strip '[' ']'
  var int_c = tokens[2].substring(1, tokens[2].length - 1);//strip '[' ']'

    console.log(str_TS.toString());
    console.log(int_p.toString());
    console.log(int_c.toString());

    var counter = {
        timestamp: parseInt(str_TS),
        PCount: parseInt(int_p),
        CCount: parseInt(int_c)
    }
    arr_counters.push(counter);
})

for (var index = 0; index < arr_counters.length; index++)
    console.log(arr_counters[index]);

但最后两行似乎被跳过了,我无法看到数组的元素: 这是当前的输出:

E:\Node-JS>node read_file2.js
[1447113604] [104] [86]
1447113604
104
86
[1447113605] [111] [91]
1447113605
111
91
[1447113606] [127] [114]
1447113606
127
114
[1447113607] [115] [105]
1447113607
115
105
[1447113608] [120] [101]
1447113608
120
101
[1447113609] [105] [100]
1447113609
105
100

如果我在推送数组中的对象后立即放置for循环,那么我会在每次迭代时添加它们时看到它们,问题是如何在填充对象后正确访问数组?

1 个答案:

答案 0 :(得分:1)

问题是你的循环在readLine完成解析之前运行。只有在通过close事件解析整个文件时,才需要调用循环。

var readline = require('readline');
var fs = require('fs');

var arr_counters = [];

var rl = readline.createInterface({        
      input : fs.createReadStream("cps.log"),
      output: process.stdout,
      terminal: false    
})

rl.on('line',function(line){
    console.log(line) //or parse line
    var tokens = line.split(" ");

  var str_TS = tokens[0].substring(1,11);   //strip '[' ']'
  var int_p = tokens[1].substring(1, tokens[1].length - 1); //strip '[' ']'
  var int_c = tokens[2].substring(1, tokens[2].length - 1);//strip '[' ']'

    console.log(str_TS.toString());
    console.log(int_p.toString());
    console.log(int_c.toString());

    var counter = {
        timestamp: parseInt(str_TS),
        PCount: parseInt(int_p),
        CCount: parseInt(int_c)
    }
    arr_counters.push(counter);
})


rl.on('close',function(){
    for (var index = 0; index < arr_counters.length; index++)
        console.log(arr_counters[index]);
});