Knowing EOF when using node.js and lazy

Problem

I have a routine written in CoffeeScript, running in node.js that reads lines from a Jade-file. It looks like this:

each_line = (file, callback) ->
last_line = null

lazy = Lazy(fs.createReadStream(file)).lines.map(String).filter (line) ->
not (
# Filter the not interesting rows in the top of the file
/^html$/i.test(line) or
/^\s+body$/i.test(line) or
/^\s+\/\/\s+Generator.*$/i.test(line)
)

lazy.forEach (line) ->
# We only emit those lines that are whole lines, multilines will become joined
if /^\t/g.test(line)
last_line += line.replace(/\t/g, '').replace(/(\r\n|\n|\r)/gm," ")
else
callback(last_line) if last_line
last_line = line.replace(/(\r\n|\n|\r)/gm," ")

Since all this runs async, I need to know EOF so that I can perform operations after the whole iteration is done. Does anyone have any suggestions?

Problem courtesy of: Fredrik Andersson

Solution

I will preface this by saying that I haven’t used Lazy myself, but I just looked at the docs.

I was somewhat expecting Lazy to emit an ‘end’ event, but I can’t tell if it does, either way you can bind a callback directly to the end event on the read stream.

each_line = (file, callback, eof_callback) ->
last_line = null

stream = fs.createReadStream file

stream.on 'end', eof_callback

lazy = Lazy(stream).lines.map(String).filter (line) ->
not (
# Filter the not interesting rows in the top of the file
/^html$/i.test(line) or
/^\s+body$/i.test(line) or
/^\s+\/\/\s+Generator.*$/i.test(line)
)

lazy.forEach (line) ->
# We only emit those lines that are whole lines, multilines will become joined
if /^\t/g.test(line)
last_line += line.replace(/\t/g, '').replace(/(\r\n|\n|\r)/gm," ")
else
callback(last_line) if last_line
last_line = line.replace(/(\r\n|\n|\r)/gm," ")

Solution courtesy of: loganfsmyth

View additional discussion.