You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lazystream.js 1.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. var util = require('util');
  2. var PassThrough = require('readable-stream/passthrough');
  3. module.exports = {
  4. Readable: Readable,
  5. Writable: Writable
  6. };
  7. util.inherits(Readable, PassThrough);
  8. util.inherits(Writable, PassThrough);
  9. // Patch the given method of instance so that the callback
  10. // is executed once, before the actual method is called the
  11. // first time.
  12. function beforeFirstCall(instance, method, callback) {
  13. instance[method] = function() {
  14. delete instance[method];
  15. callback.apply(this, arguments);
  16. return this[method].apply(this, arguments);
  17. };
  18. }
  19. function Readable(fn, options) {
  20. if (!(this instanceof Readable))
  21. return new Readable(fn, options);
  22. PassThrough.call(this, options);
  23. beforeFirstCall(this, '_read', function() {
  24. var source = fn.call(this, options);
  25. var emit = this.emit.bind(this, 'error');
  26. source.on('error', emit);
  27. source.pipe(this);
  28. });
  29. this.emit('readable');
  30. }
  31. function Writable(fn, options) {
  32. if (!(this instanceof Writable))
  33. return new Writable(fn, options);
  34. PassThrough.call(this, options);
  35. beforeFirstCall(this, '_write', function() {
  36. var destination = fn.call(this, options);
  37. var emit = this.emit.bind(this, 'error');
  38. destination.on('error', emit);
  39. this.pipe(destination);
  40. });
  41. this.emit('writable');
  42. }