我正在尝试延迟读取文件,但是我无法使用 each()
。
我想读取一个文件的第一行,然后读取另一个文件的第一行,依此类推。
我正在尝试使用迭代器,但没有成功。 这是我的代码:
var Lazy = require('lazy.js');
var it = Lazy.readFile("log.txt")
.lines()
.getIterator();
while(it.moveNext()){
console.log(it.current());
}
Lazy.readFile("log.txt").lines().size()
返回 0。
但是,这工作正常:
Lazy.readFile("log.txt")
.lines()
.each(function(line){
console.log(line);
});
最佳答案
这是 Lazy.js 的一部分,我承认我没有很好地解释它。让我复制 the current documentation for the getIterator
method 中的片段这里:
This method is used when asynchronously iterating over sequences. Any type inheriting from Sequence must implement this method or it can't support asynchronous iteration.
Note that this method is not intended to be used directly by application code. Rather, it is intended as a means for implementors to potentially define custom sequence types that support either synchronous or asynchronous iteration.
您在这里遇到的问题是,Lazy.readFile
返回一个异步序列。因此 getIterator
将不起作用,因为 Iterator
类型仅公开同步接口(interface)。
自从你发布这个问题以来,我实际上已经更新了 Lazy.js;从 0.3.2 开始,在异步序列上调用 getIterator
will throw an exception .
关于Node.js + 懒惰 : Iterate file lines,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20927826/