SEAPUNK / stream-to-generator

Convert Node.js streams to generator functions
4 stars 0 forks source link

stream-to-generator

npm version javascript standard style travis build coveralls coverage david dependencies david dev dependencies

Convert Node.js readable streams to generator functions

npm install stream-to-generator


usage

import streamToGenerator from 'stream-to-generator'
import fs from 'fs'

async function main () {
  const fileLoc = path.join(__dirname, 'fixtures/LARGE_FILE')
  const readStream = fs.createReadStream(fileLoc)
  const data = await streamToGenerator(readStream, readHandler)
}

function * readHandler (read, finish) {
  let chunks = []

  let done, chunk
  while (true) {
    ;[done, chunk] = yield read()
    if (done) break
    chunks.push(chunk)
  }

  return yield finish(Buffer.concat(chunks))
}

api

streamToGenerator(readStream, handlerFunction)

Converts a readable stream to a generator function.

readStream is a readable stream.

handlerFunction is a generator function that takes two arguments:

Returns a Promise, which is resolved with retval when the readHandler calls finish(retval). Otherwise, the Promise is rejected with an error if the stream or handler function encounters an error.