在 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