Skip to content

Instantly share code, notes, and snippets.

@japboy
Last active December 18, 2015 04:58
Show Gist options
  • Select an option

  • Save japboy/5728740 to your computer and use it in GitHub Desktop.

Select an option

Save japboy/5728740 to your computer and use it in GitHub Desktop.
'use strict'
#
# Line oriented process
#
# Based on:
# http://paulownia.hatenablog.com/entry/2012/09/29/024439
#
# Usage:
#
# fs = require 'fs'
# linereader = require './linereader'
#
# stream = fs.createReadStream './text.txt'
#
# reader = new linereader.LineReader stream
# reader.on 'line', (line) -> process.stdout.write "> #{line}"
# reader.read()
#
events = require 'events'
class LineReader extends events.EventEmitter
_buf: undefined
_stream: undefined
read: =>
@_stream.resume()
destroy: =>
@_buf = ''
@_stream.destroy()
_onStreamData: (chunk) =>
@_stream.pause()
@_buf += chunk
searchLine = =>
i = @_buf.indexOf '\n'
if 0 <= i
line = @_buf.slice(0, i + 1)
@_buf = @_buf.slice i + 1
@emit 'line', line
process.nextTick searchLine
else
@_stream.resume()
searchLine()
_onStreamEnd: =>
@_buf = ''
@destroy()
_onStreamClose: =>
@emit 'close'
constructor: (stream) ->
@_buf = ''
@_stream = stream or process.stdin
@_stream.on 'data', @_onStreamData
@_stream.on 'end', @_onStreamEnd
@_stream.on 'close', @_onStreamClose
@_stream.setEncoding 'utf8'
exports.LineReader = LineReader
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment