Skip to content

Instantly share code, notes, and snippets.

@TooTallNate
Created February 10, 2012 01:11
Show Gist options
  • Save TooTallNate/1785026 to your computer and use it in GitHub Desktop.
Save TooTallNate/1785026 to your computer and use it in GitHub Desktop.
Make any ReadableStream emit "line" events
/**
* A quick little thingy that takes a Stream instance and makes
* it emit 'line' events when a newline is encountered.
*
* Usage:
* ‾‾‾‾‾
* emitLines(process.stdin)
* process.stdin.resume()
* process.stdin.setEncoding('utf8')
* process.stdin.on('line', function (line) {
* console.log(line event:', line)
* })
*
*/
function emitLines (stream) {
var backlog = ''
stream.on('data', function (data) {
backlog += data
var n = backlog.indexOf('\n')
// got a \n? emit one or more 'line' events
while (~n) {
stream.emit('line', backlog.substring(0, n))
backlog = backlog.substring(n + 1)
n = backlog.indexOf('\n')
}
})
stream.on('end', function () {
if (backlog) {
stream.emit('line', backlog)
}
})
}
module.exports = emitLines
var assert = require('assert')
, emitLines = require('./emitLines')
, Stream = require('stream')
, stream
, count
// 1
count = 0
stream = new Stream
stream.on('line', function (line) {
count++
assert.equal('test', line)
})
emitLines(stream)
assert.equal(0, count)
stream.emit('data', Buffer('test\n'))
assert.equal(1, count)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment