Created
February 20, 2012 20:09
-
-
Save swoodtke/1871105 to your computer and use it in GitHub Desktop.
Class to read a file line-by-line in Node.js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
fs = require 'fs' | |
path = require 'path' | |
events = require 'events' | |
class LineReader extends events.EventEmitter | |
constructor: -> | |
@stream = null | |
@saved = null | |
_endStream: -> | |
return if not @stream | |
@stream = null | |
if @saved | |
@emit 'line' | |
@saved = null | |
@emit 'end' | |
open: (filename) -> | |
@stream = fs.createReadStream(filename) | |
@stream.setEncoding 'utf-8' | |
@stream.on 'error', (err) => @.emit 'error', err | |
@stream.on 'end', => @_endStream() | |
@stream.on 'close', => @_endStream() | |
@stream.on 'data', (data) => | |
data = @saved + data if @saved | |
newline = data.indexOf '\n' | |
while newline != -1 | |
@emit 'line', data.substr 0, newline+1 | |
data = data.substr newline+1 | |
newline = data.indexOf '\n' | |
@saved = data | |
return @ | |
close: -> | |
@stream.destroy() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment