Skip to content

Instantly share code, notes, and snippets.

@mhart
Last active September 12, 2016 00:29
Show Gist options
  • Save mhart/37da9892df56d34cfa4165d439052d71 to your computer and use it in GitHub Desktop.
Save mhart/37da9892df56d34cfa4165d439052d71 to your computer and use it in GitHub Desktop.
Split stream for Node.js >= 4.x
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