# node.js 按行解析文件/日志

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

let fileName = "test.log";
readFileToArr(fileName, function(arr) {
    // console.log(arr)
});


/*
* 按行读取文件内容
* 返回:字符串数组
* 参数:fReadName:文件名路径
*      callback:回调函数
* */
function readFileToArr(fReadName,callback){
    var fRead = fs.createReadStream(fReadName);
    var objReadline = readline.createInterface({
        input:fRead
    });
    var arr = new Array();
    objReadline.on('line',function (line) {
        // arr.push(line);
        var dateStr = line.substring(11,16);
        let start = "00:00";
        let end = "11:17";
        let v1 = compareTime(dateStr, start);
        let v2 = compareTime(dateStr, end);
        if(!v1 && v2) {
            fs.appendFileSync("2.txt",line + "\n");
            // arr.push(line);
        }
    });
    objReadline.on('close',function () {
       // console.log(arr);
        callback(arr);
    });
}

function compareTime(t1, t2) {
    var date = new Date();
    var a = t1.split(":");
    var b = t2.split(":");
    return date.setHours(a[0],a[1]) < date.setHours(b[0],b[1]);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45