index.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. 'use strict';
  2. var Writable = require('readable-stream').Writable;
  3. var inherits = require('util').inherits;
  4. var Promise = require('pinkie-promise');
  5. function BufferStream() {
  6. Writable.call(this, { objectMode: true });
  7. this.buffer = [];
  8. this.length = 0;
  9. }
  10. inherits(BufferStream, Writable);
  11. BufferStream.prototype._write = function(chunk, enc, next) {
  12. if (!Buffer.isBuffer(chunk)) {
  13. chunk = new Buffer(chunk);
  14. }
  15. this.buffer.push(chunk);
  16. this.length += chunk.length;
  17. next();
  18. };
  19. module.exports = function read(stream, options, cb) {
  20. if (!stream) {
  21. throw new Error('stream argument is required');
  22. }
  23. if (typeof options === 'function') {
  24. cb = options;
  25. options = {};
  26. }
  27. if (typeof options === 'string' || options === undefined || options === null) {
  28. options = { encoding: options };
  29. }
  30. if (options.encoding === undefined) { options.encoding = 'utf8'; }
  31. var promise;
  32. if (!cb) {
  33. var resolve, reject;
  34. promise = new Promise(function(_res, _rej) {
  35. resolve = _res;
  36. reject = _rej;
  37. });
  38. cb = function (err, data) {
  39. if (err) { return reject(err); }
  40. resolve(data);
  41. };
  42. }
  43. var sink = new BufferStream();
  44. sink.on('finish', function () {
  45. var data = Buffer.concat(this.buffer, this.length);
  46. if (options.encoding) {
  47. data = data.toString(options.encoding);
  48. }
  49. cb(null, data);
  50. });
  51. stream.once('error', cb);
  52. stream.pipe(sink);
  53. return promise;
  54. }