Node.js + Lazy: Iterate file lines

Problem

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);
        });
Problem courtesy of: ffleandro

Solution

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.

Solution courtesy of: Dan Tao

Discussion

There is currently no discussion for this recipe.

This recipe can be found in it's original form on Stack Over Flow.