index.js 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. var util = require('util');
  2. var Transform = require('stream').Transform;
  3. util.inherits(SliceStream, Transform);
  4. function SliceStream(start, end) {
  5. if (!(this instanceof SliceStream)) {
  6. return new SliceStream();
  7. }
  8. Transform.call(this);
  9. this._start = start || 0;
  10. this._end = end || Infinity;
  11. this._offset = 0;
  12. this._state = 0;
  13. this._emitUp = false;
  14. this._emitDown = false;
  15. }
  16. SliceStream.prototype._transform = function(chunk, encoding, done) {
  17. this._offset += chunk.length;
  18. if (!this._emitUp && this._offset >= this._start) {
  19. this._emitUp = true;
  20. var start = chunk.length - (this._offset - this._start);
  21. if(this._offset > this._end)
  22. {
  23. var end = chunk.length - (this._offset - this._end);
  24. this._emitDown = true;
  25. this.push(chunk.slice(start, end));
  26. }
  27. else
  28. {
  29. this.push(chunk.slice(start, chunk.length));
  30. }
  31. return done();
  32. }
  33. if (this._emitUp && !this._emitDown) {
  34. if (this._offset >= this._end) {
  35. this._emitDown = true;
  36. this.push(chunk.slice(0, chunk.length - (this._offset - this._end)));
  37. } else {
  38. this.push(chunk);
  39. }
  40. return done();
  41. }
  42. return done();
  43. }
  44. exports.slice = function(start, end) {
  45. return new SliceStream(start, end);
  46. }