简体   繁体   中英

Node.js + Lazy: Iterate file lines

I'm trying to lazy read a file, however I can't use 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. 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.

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. Let me copy a snippet from the current documentation for the getIterator method here:

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.

The issue you've run into here is that Lazy.readFile returns an asynchronous sequence. So getIterator will not work, because the Iterator type only exposes a synchronous interface.

I've actually updated Lazy.js since you posted this question; as of 0.3.2, calling getIterator on an async sequence will throw an exception .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM