Last active
September 12, 2016 00:29
-
-
Save mhart/37da9892df56d34cfa4165d439052d71 to your computer and use it in GitHub Desktop.
Split stream for Node.js >= 4.x
This file contains hidden or 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 stream = require('stream') | |
module.exports = split | |
function split(delim, emitTrailingIfEmpty) { | |
delim = delim || new Buffer('\n') | |
var trailing, delimLen = delim.length | |
return new stream.Transform({ | |
readableObjectMode: true, | |
transform: function(chunk, enc, cb) { | |
var ix, offset = 0, firstOffset = trailing ? trailing.length : 0 | |
if (firstOffset) chunk = Buffer.concat([trailing, chunk]) | |
while ((ix = chunk.indexOf(delim, offset || firstOffset)) != -1) { | |
this.push(chunk.slice(offset, ix)) | |
offset = ix + delimLen | |
} | |
trailing = offset ? chunk.slice(offset) : chunk | |
cb() | |
}, | |
flush: function(cb) { | |
if (trailing && (trailing.length || emitTrailingIfEmpty)) this.push(trailing) | |
cb() | |
}, | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment