开发者

Knowing EOF when using node.js and lazy

开发者 https://www.devze.com 2023-03-25 17:04 出处:网络
I have a routine written in CoffeeScript, running in node.js that reads lines from a Jade-file. It looks like this:

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 be开发者_JAVA技巧come 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?


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," ")


I believe Lazy will emit an 'end' event on the original Lazy object that was created:

Lazy = require('lazy')
fs = require('fs')

readLines = (filename, next) ->
  lazy = new Lazy(fs.createReadStream(filename))
  lazy.on 'end', ->
    if next then next null
  lazy.lines.forEach (line) ->
    console.log 'Read line:', line.toString()

readLines process.argv[1], ->
  console.log 'All done.'
0

精彩评论

暂无评论...
验证码 换一张
取 消