Package Exports
- awaitify-stream
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (awaitify-stream) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
node-awaitify-stream
Read or write to a stream using while
and await
, not event handlers.
Requirements
- Node v8+ recommended.
async
/await
support was added in Node v7. Node v6 will throwSyntaxError: Unexpected token function
for the examples below.
Install
npm install awaitify-stream
Read functions
- readAsync([size]): Promise wrapper around readable.read. Returns a promise for the next chunk of data. Resolves to null at the end of the stream.
Write functions
writeAsync(chunk[, encoding]): Promise wrapper around writable.write. Returns a promise that resolves following a
drain
event (if necessary) and a call towrite
. Doesn't wait for the supplied chunk to be flushed.endAsync([chunk][, encoding]): Promise wrapper around writable.end. Returns a promise that resolves when the stream is finished.
Reader/Writer API
Use createReader
, createWriter
or createDuplexer
to get a wrapper around the stream.
const fs = require('fs');
const aw = require('awaitify-stream');
async function run() {
let readStream = fs.createReadStream('firstExample.js');
let reader = aw.createReader(readStream);
let writer = aw.createWriter(process.stdout);
// Read the file and write it to stdout.
let chunk;
while (null !== (chunk = await reader.readAsync())) {
// Perform any synchronous or asynchronous operation here.
await writer.writeAsync(chunk);
}
}
run();
Augment Stream API
Use addAsyncFunctions
to add the reader and/or writer functions to a stream object.
const fs = require('fs');
const aw = require('awaitify-stream');
const lineLength = 6; // 5 + the newline character.
function delay(ms) {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
async function run() {
let readStream = aw.addAsyncFunctions(fs.createReadStream('zipCodes.txt'));
readStream.setEncoding('utf8');
// print zip codes, slowly.
let zipCode;
while (null !== (zipCode = await readStream.readAsync(lineLength))) {
// Remove the newline character. If you didn't set the encoding
// above, use zipCode.toString().trim()
zipCode = zipCode.trim();
console.log(zipCode);
await delay(200);
}
}
run();