Count Words with for await
Medium · Streams
Readable streams in Node are async iterables, so you can read them with for await (const chunk of stream). The starter has createReadStream(chunks), an async generator that stands in for fs.createReadStream and yields text chunks one by one after a tiny delay.
Write async countWords(stream) that reads the stream with for await...of and returns { words, longest }:
- A word is a run of non-whitespace characters (spaces, tabs and newlines separate words).
- A word can be split across chunks: "hel" + "lo world" is 2 words.
- longest is the longest word (the first one if several have the same length), or "" when there are no words.
The driver runCountWords(chunks) is already written. It creates a stream from the chunks and returns the result of countWords(stream).