使用 generator 按行读取文件的库,co-readline
co-readline
Read a file line by line in generator/co style.
install
$ npm i co-readline
easy example
var coReadline = require('co-readline')
var co = require('co')
co(function * () {
var NORMAL_FILE_PATH = 'absolute_path_to_file'
var rlGen = coReadline(NORMAL_FILE_PATH)
var lines = []
for (var line of rlGen) {
if (line.then) { // `line` could be Promise or String
line = yield line;
}
lines.push(line)
}
var fileContent = yield fs.readFile(NORMAL_FILE_PATH, 'utf-8')
fileContent.should.equal(lines.join('\n'))
})
api
coReadline(filePath)
return a generator, then do for..of
to it
benchmark
About 1/3 speed of build-in readline
module
About 1/6 speed of fs.readFileSync
Read about 1 million lines per second
3 回复
那么晚发 给你个满分先
赞!
报个小 bug 吧,debug 模块最好放到 dependencies
里,要不可能会报错的。
这里其实可以不用 co 的 :)
(async function x() {
const PATH = "./index.js";
const rlGen = readline(PATH);
const lines = [];
for await (const line of rlGen) {
lines.push(line);
}
console.log(lines);
})();
(注:需要经过 babel-preset-stage-3)
还有个建议,可以把 gen
函数名改成 [Symbol.asyncIterator]
,这可以直接支持以后的 Asynchronous iteration。
- debug 模块确实如你所说,感谢建议
- 只是测试代码用了 co 而已,库本身都是 Promise 的。await 那一套我懒得搞编译
- gen [Symbol.asyncIterator] 这一点,你提到的知识点太新了。。。等它发布然后有人提 pr 再说。。。