UNPKG

chunker

Version:

Chunk/split your stream without eating the splitter char.

64 lines (56 loc) 2.14 kB
// Generated by CoffeeScript 1.6.3 var __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }; module.exports = (function() { var Chunker, stream; stream = require('stream'); return Chunker = (function(_super) { __extends(Chunker, _super); Chunker.prototype.leftover = null; Chunker.prototype.matcher = new Buffer('\r\n'); function Chunker(options) { Chunker.__super__.constructor.call(this, options); if (options && options.matcher) { this.matcher = options.matcher; if (typeof this.matcher === 'string') { this.matcher = new Buffer(this.matcher); } } } Chunker.prototype._transform = function(chunk, encoding, callback) { var i, j, match, matched, part, pivot, skip, start, _i, _j, _ref, _ref1; pivot = this.matcher[this.matcher.length - 1]; matched = false; match = -1; start = 0; skip = 0; if (this.leftover) { chunk = Buffer.concat([this.leftover, chunk], this.leftover.length + chunk.length); skip = this.leftover.length - this.matcher.length; this.leftover = null; } for (i = _i = skip, _ref = chunk.length; _i < _ref; i = _i += 1) { if (chunk[i] !== pivot) { continue; } match = i; for (j = _j = i, _ref1 = i - this.matcher.length; _j > _ref1; j = _j += -1) { if (chunk[j] === this.matcher[this.matcher.length - i + j - 1]) { continue; } match = -1; } if (match > -1) { part = chunk.slice(start, match + 1); start = match + 1; this.leftover = chunk.slice(start); this.push(part); this.emit('chunk', part); } } this.leftover = chunk.slice(start); return callback(null); }; return Chunker; })(stream.Transform); })();