具体代码实现如下:
var fs = require("fs");
var readLine = require("readline");
/**
* 按行读取文件内容
*
* @param fReadName 文件名路径
* @param cb 回调函数
*
* @return 字符串数组
*/
function readFileToArr(fReadName, cb) {
var arr = [];
var readObj = readLine.createInterface({
input: fs.createReadStream(fReadName)
});
readObj.on('line', function (line) {
arr.push(line);
});
readObj.on('close', function () {
console.log('readLine close....');
cb(arr);
});
}
readFileToArr('ObserverMode.js', function (arr) {
console.log(arr);
});
使用到的实例代码如下:
//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 = '李四';
示例执行结果如下:
"D:\software\WebStorm 2017.2.4\bin\runnerw.exe" "D:\Program Files\nodejs\node.exe" D:\Workspaces\Webstorm\web\javascript\ES6\src\readFileToArr.js
readLine close....
[ '',
'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 = \'李四\';',
'' ]
Process finished with exit code 0