ES5 使用 NodeJS 逐行读取文件的内容

参考:
ES6 使用 NodeJS 逐行读取文件内容

在 ES5 中使用 NodeJS 逐行读取文件的内容,下面是具体的代码实现。

目录结构如下
在这里插入图片描述

//ObserverMode.js

const queuedObservers = new Set();

const observe = fn => queuedObservers.add(fn);
const observable = obj => new Proxy(obj, {set});

function set(target, key, value, receiver) {
    const result = Reflect.set(target, key, value, receiver);
    queuedObservers.forEach(observer => observer());
    return result;
}

const person = observable({
    name: '张三',
    age: 20
});

function print() {
    console.log(`${person.name}, ${person.age}`)
}

observe(print);
person.name = '李四';
//readFileByLine.js
(function (global) {
    var fs = require("fs");
    var readLine = require("readline");

    function readByLine(file, cb) {
        var is = fs.createReadStream(file);

        var readObj = readLine.createInterface({
            input: is
        });

        readObj.on("line", cb);

        readObj.on("close", () => {
            console.log("readLine closed ....");
        });
    }
    global.readFileByLine = readByLine;
})(global);

var idx = 0;
readFileByLine("ObserverMode.js", function (line) {
    var out = "line_" + idx++ + ": " + line.toString();
    console.log(out);
});

直接 Run ‘readFileByLine.js’

最后输出结果如下:

"D:\software\WebStorm 2017.2.4\bin\runnerw.exe" "D:\Program Files\nodejs\node.exe" D:\Workspaces\Webstorm\web\javascript\ES6\src\readFileByLine.js
line_0: 
line_1: const queuedObservers = new Set();
line_2: 
line_3: const observe = fn => queuedObservers.add(fn);
line_4: const observable = obj => new Proxy(obj, {set});
line_5: 
line_6: function set(target, key, value, receiver) {
line_7:     const result = Reflect.set(target, key, value, receiver);
line_8:     queuedObservers.forEach(observer => observer());
line_9:     return result;
line_10: }
line_11: 
line_12: const person = observable({
line_13:     name: '张三',
line_14:     age: 20
line_15: });
line_16: 
line_17: function print() {
line_18:     console.log(`${person.name}, ${person.age}`)
line_19: }
line_20: 
line_21: observe(print);
line_22: person.name = '李四';
line_23: 
readLine closed ....

Process finished with exit code 0
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值