gpt4 book ai didi

node.js - Node js中的语句顺序

转载 作者:搜寻专家 更新时间:2023-11-01 00:00:51 25 4
gpt4 key购买 nike

Node JS 的新手,仍在习惯做事的方式。我正在处理具有这种结构的文件:

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

我逐行读取它,解析每一行并创建具有 3 个属性(时间戳、计数 1、计数 2)的对象,然后我将新创建的对象添加到数组中,最后我想遍历数组并使用 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 循环,那么我会在每次迭代时看到它们被添加,问题是我如何在数组中填充对象后正确访问数组?

最佳答案

问题是您的循环在 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]);
});

关于node.js - Node js中的语句顺序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33675451/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com