public
Last active

Make any ReadableStream emit "line" events

  • Download Gist
emitLines.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34
/**
* 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
test.js
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
 
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)

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.