Created
February 10, 2012 01:11
-
-
Save TooTallNate/1785026 to your computer and use it in GitHub Desktop.
Make any ReadableStream emit "line" events
This file contains 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
/** | |
* 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 |
This file contains 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
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