slicestream.js 854 B

12345678910111213141516171819202122232425262728293031323334
  1. 'use strict';
  2. module.exports = SliceStream;
  3. var Transform = require('readable-stream/transform');
  4. var inherits = require("util").inherits;
  5. inherits(SliceStream, Transform);
  6. function SliceStream(opts, sliceFn) {
  7. if (!(this instanceof SliceStream)) {
  8. return new SliceStream(opts, sliceFn);
  9. }
  10. this._opts = opts;
  11. this._accumulatedLength = 0;
  12. this.sliceFn = sliceFn;
  13. Transform.call(this);
  14. }
  15. SliceStream.prototype._transform = function (chunk, encoding, callback) {
  16. this._accumulatedLength += chunk.length;
  17. if (this._accumulatedLength >= this._opts.length) {
  18. //todo handle more than one slice in a stream
  19. var offset = chunk.length - (this._accumulatedLength - this._opts.length);
  20. this.sliceFn(chunk.slice(0, offset), true, chunk.slice(offset));
  21. callback();
  22. } else {
  23. this.sliceFn(chunk);
  24. callback();
  25. }
  26. };