all files / stream-read-all/ index.js

95.83% Statements 23/24
80% Branches 8/10
100% Functions 4/4
95.83% Lines 23/24
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55                                                               
'use strict'
const Transform = require('stream').Transform
 
/**
 * @module stream-read-all
 */
module.exports = streamReadAll
 
class StreamReader extends Transform {
  constructor (options) {
    super(options)
    this.options = options || {}
    if (this.options.objectMode) {
      this.buf = []
    } else {
      this.buf = Buffer.alloc ? Buffer.alloc(0) : new Buffer(0)
    }
  }
 
  _transform (chunk, enc, done) {
    Eif (chunk) {
      if (this.options.objectMode) {
        this.buf.push(chunk)
      } else {
        this.buf = Buffer.concat([ this.buf, chunk ])
      }
    }
    done()
  }
 
  _flush (done) {
    this.push(this.buf)
    this.push(null)
    done()
  }
}
 
/**
 * @return {Promise}
 * @alias module:stream-read-all
 */
function streamReadAll (stream, options) {
  const streamReader = new StreamReader(options)
  stream.pipe(streamReader)
  return new Promise((resolve, reject) => {
    streamReader.resume()
    streamReader.on('end', () => {
      resolve(streamReader.buf)
    })
    streamReader.on('error', (err) => {
      reject(err)
    })
  })
}