npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

awaitify-stream

v1.0.2

Published

Read or write to a stream using while and await, not event handlers.

Downloads

2,991

Readme

node-awaitify-stream

Read or write to a stream using while and await, not event handlers.

  • Read and write streams using familiar constructs, without resorting to synchronous methods for I/O.
  • Read and write long streams without runaway memory usage.
  • Process streams one chunk or line at a time. Await asynchronous operations inbetween.

Requirements

  • Node v8+ recommended. async/await support was added to Node v7. Node v6 will throw "SyntaxError: Unexpected token function" for the examples below. See secondExample_without_await.js for an example of using awaitify-stream without await.

Install

npm install awaitify-stream

Reader 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.

Writer functions

  • writeAsync(chunk[, encoding]): Promise wrapper around writable.write. Returns a promise that resolves following a drain event (if necessary) and a call to write. Doesn't wait for the 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 create a wrapper around the stream. The stream property can be used to later access 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, count = 0;
    while (null !== (chunk = await reader.readAsync())) {
        // Perform any synchronous or asynchronous operation here.
        await writer.writeAsync(chunk);
        count++;
    }

    console.log(`\n\nDone. Read the file in ${count} chunk(s).`);
}

run();

Augment Stream API

Use addAsyncFunctions to add the reader and/or writer functions to a stream object. The reader functions are added if stream.readable is true. The writer functions are added if stream.writable is true.

const fs = require('fs');
const aw = require('awaitify-stream');
const lineLength = 6; // 5 digits in a zip code, plus the newline character.

function delay(ms) {
    return new Promise((resolve) => {
        setTimeout(resolve, ms);
    });
}

async function run() {
    let stream = aw.addAsyncFunctions(fs.createReadStream('zipCodes.lftxt'));
    stream.setEncoding('utf8');

    // Read and print zip codes, slowly.
    let zipCode;
    while (null !== (zipCode = await stream.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();

Line Reading

You can use awaitify-stream in combination with a package like byline to read a line at a time.

const fs = require('fs');
const aw = require('awaitify-stream');
const byline = require('byline');
const readline = require('readline'); // Used for prompting the user.

function checkGuess(rl, guess) {
    return new Promise((resolve) => {
        rl.question(`Is the ${guess} your card? [y/n] `, (answer) => {
            resolve(answer.startsWith('y'));
        });
    });
}

async function run() {
    let stream = fs.createReadStream('millionsOfGuesses.txt');
    stream.setEncoding('utf8');

    let lineStream = byline.createStream(stream, { keepEmptyLines: false });
    let reader = aw.createReader(lineStream);

    const rl = readline.createInterface({
        input: process.stdin,
        output: process.stdout
    });

    try {
        let line;
        while (null !== (line = await reader.readAsync())) {
            let guessedCard = await checkGuess(rl, line);

            if (guessedCard) {
                console.log('Huzzah!');
                return;
            }
        }

        console.log('Drat!');
    }
    finally {
        rl.close();
    }
}

run();

Related Packages

  • byline: Useful for reading streams line-by-line. I recommend using byline over node's builtin readline because you can pause the stream or await asynchronous operations inbetween each line.

  • stream-consume-promise: Similar to this package, but returns an iterator-style response with value and done properties. Also see stream-produce-promise.

Notes

  • The library has no dependencies. mocha and byline are required only for testing.

Credits

byline served as an example package as I was writing awaitify-stream, my first package.

davedoesdev contributed fixes.

mknj identified an issue with error handling.