stream-to-generator
Convert Node.js readable streams to generator functions
npm install stream-to-generator
usage
{ const fileLoc = path const readStream = fs const data = await } { let chunks = let done chunk while true ;done chunk = if done break chunks return }
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 withyield
. 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 aread()
afterend == true
will throw an error.data
is the next chunk of data gathered from the stream. Ifend == true
, data will be undefined.
finish(retval)
Creates a request to end the handler. This resolves the created promise from callingstreamToGenerator()
withretval
. This should be done withyield
(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.