0.1.1 • Published 7 years ago

stream-to-generator v0.1.1

Weekly downloads
34
License
MIT
Repository
github
Last release
7 years ago

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:

  • read() Creates a request for more data in the stream. This must be done with yield. If data could not be read, then the handler function is cancelled. This returns an array: [end, data]:
    • end is a Boolean, which indicates whether there will be more data or not. Yielding a read() after end == true will throw an error.
    • data is the next chunk of data gathered from the stream. If end == true, data will be undefined.
  • finish(retval) Creates a request to end the handler. This resolves the created promise from calling streamToGenerator() with retval. This should be done with yield (the wrapper will be able to cancel the generator), but not required to.

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.