0.1.1 • Published 9 years ago
stream-to-generator v0.1.1
stream-to-generator
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 withyield. If data could not be read, then the handler function is cancelled. This returns an array:[end, data]:endis a Boolean, which indicates whether there will be more data or not. Yielding aread()afterend == truewill throw an error.datais 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.