bl.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. 'use strict'
  2. const DuplexStream = require('readable-stream').Duplex
  3. const inherits = require('inherits')
  4. const BufferList = require('./BufferList')
  5. function BufferListStream (callback) {
  6. if (!(this instanceof BufferListStream)) {
  7. return new BufferListStream(callback)
  8. }
  9. if (typeof callback === 'function') {
  10. this._callback = callback
  11. const piper = function piper (err) {
  12. if (this._callback) {
  13. this._callback(err)
  14. this._callback = null
  15. }
  16. }.bind(this)
  17. this.on('pipe', function onPipe (src) {
  18. src.on('error', piper)
  19. })
  20. this.on('unpipe', function onUnpipe (src) {
  21. src.removeListener('error', piper)
  22. })
  23. callback = null
  24. }
  25. BufferList._init.call(this, callback)
  26. DuplexStream.call(this)
  27. }
  28. inherits(BufferListStream, DuplexStream)
  29. Object.assign(BufferListStream.prototype, BufferList.prototype)
  30. BufferListStream.prototype._new = function _new (callback) {
  31. return new BufferListStream(callback)
  32. }
  33. BufferListStream.prototype._write = function _write (buf, encoding, callback) {
  34. this._appendBuffer(buf)
  35. if (typeof callback === 'function') {
  36. callback()
  37. }
  38. }
  39. BufferListStream.prototype._read = function _read (size) {
  40. if (!this.length) {
  41. return this.push(null)
  42. }
  43. size = Math.min(size, this.length)
  44. this.push(this.slice(0, size))
  45. this.consume(size)
  46. }
  47. BufferListStream.prototype.end = function end (chunk) {
  48. DuplexStream.prototype.end.call(this, chunk)
  49. if (this._callback) {
  50. this._callback(null, this.slice())
  51. this._callback = null
  52. }
  53. }
  54. BufferListStream.prototype._destroy = function _destroy (err, cb) {
  55. this._bufs.length = 0
  56. this.length = 0
  57. cb(err)
  58. }
  59. BufferListStream.prototype._isBufferList = function _isBufferList (b) {
  60. return b instanceof BufferListStream || b instanceof BufferList || BufferListStream.isBufferList(b)
  61. }
  62. BufferListStream.isBufferList = BufferList.isBufferList
  63. module.exports = BufferListStream
  64. module.exports.BufferListStream = BufferListStream
  65. module.exports.BufferList = BufferList