Skip to content

Instantly share code, notes, and snippets.

@dshaw
Forked from TooTallNate/emitLines.js
Created February 10, 2012 01:24
Show Gist options
  • Save dshaw/1785167 to your computer and use it in GitHub Desktop.
Save dshaw/1785167 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)
}
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment