[英]Node.js + Lazy: Iterate file lines
I'm trying to lazy read a file, however I can't use each()
. 我试图懒惰地读取文件,但是我不能使用
each()
。 I want to read the first line of a file, then the first of another file, and so on. 我想读取文件的第一行,然后读取另一个文件的第一行,依此类推。
I'm trying to use the Iterator, but with no success. 我正在尝试使用Iterator,但没有成功。 This is my code:
这是我的代码:
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()
returns 0. Lazy.readFile("log.txt").lines().size()
返回0。
However, this works fine: 但是,这很好用:
Lazy.readFile("log.txt")
.lines()
.each(function(line){
console.log(line);
});
This is a part of Lazy.js that I admittedly haven't done a great job of explaining. 这是Lazy.js的一部分,我承认我并没有做出色的解释。 Let me copy a snippet from the current documentation for the
getIterator
method here: 让我从当前文档中为
getIterator
方法复制一个代码段:
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.
从Sequence继承的任何类型都必须实现此方法,否则它不能支持异步迭代。
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.
相反,它旨在作为实现者潜在地定义支持同步或异步迭代的自定义序列类型的一种手段。
The issue you've run into here is that Lazy.readFile
returns an asynchronous sequence. 您在这里遇到的问题是
Lazy.readFile
返回异步序列。 So getIterator
will not work, because the Iterator
type only exposes a synchronous interface. 所以
getIterator
将不起作用,因为Iterator
类型仅公开一个同步接口。
I've actually updated Lazy.js since you posted this question; 自从您发布此问题以来,我实际上已经更新了Lazy.js。 as of 0.3.2, calling
getIterator
on an async sequence will throw an exception . 从0.3.2开始,在异步序列上调用
getIterator
将引发异常 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.