Logo

dev-resources.site

for different kinds of informations.

Working with streams in Node.js

Published at
4/9/2023
Categories
javascript
typescript
node
streams
Author
padcom
Author
6 person written this
padcom
open
Working with streams in Node.js

When working with streams one of the coolest things ever is using async generators to do piped processing. Let's start with a simple example that generates numbers from 1 to 5:

const numbers = async function* () {
  for (let i = 0; i < 5; i++) yield i.toString()
}
Enter fullscreen mode Exit fullscreen mode

This generator yields 5 numbers, 0 through 4, as strings. Let's pipe them through to see them on the screen:

Readable.from(numbers()).pipe(process.stdout)
Enter fullscreen mode Exit fullscreen mode

Boom! Just like that, we're printing the content of the stream to standard output. Let's see how we can do the printing using console.log():

const logger = async function* (
  source: AsyncGenerator<string>
) {
  for await (const number of source) {
    console.log(number)
  }
}

Readable.from(numbers())
  .pipe(Duplex.from(logger))
  .resume()
Enter fullscreen mode Exit fullscreen mode

The call to Readable.resume() at the end makes the stream pull all the values and process them.

What's interesting here is that we're using a Duplex stream created from an async generator. Since it is a Duplex stream (so Readable and Writeable) we can still process the data further. For example, we can augment the numbers with some description:

const augmenter = async function* (source: AsyncGenerator<string>) {
  for await (const number of source) {
    yield `This is number ${number}`
  }
}

Readable.from(numbers())
  .pipe(Duplex.from(augmenter))
  .pipe(Duplex.from(logger))
  .resume()
Enter fullscreen mode Exit fullscreen mode

Please note that the source argument to all the generators have a generic type, that will determine the type of element we are iterating over. In our case, the generic type is string so the number variable is of type string.

I think that's totally cool - how about you?

Happy coding!

streams Article's
30 articles in total
Favicon
How does Optional.ifPresent() differ from Optional.orElse()?
Favicon
Beyond the Basics: Mastering Streams in Node.JS
Favicon
The streaming bridges — A Kafka, RabbitMQ, MQTT and CoAP example
Favicon
Java Streams | What is the difference between sorted() and distinct() in streams?
Favicon
How to handle large file uploads in SvelteKit using streams
Favicon
Execução preguiçosa com Lambdas
Favicon
Руководство по Java 8 Stream API
Favicon
In Java how to create a custom ArrayList that doesn't allow duplicate? #Interview Question
Favicon
Why Set Doesn't Allow Duplicates in Java
Favicon
Optional Class in Java and its methods
Favicon
A Few About: Streams NodeJs (PT-BR)
Favicon
File reading in python
Favicon
Asynchronous Streams in C#: Effortless Async Data Processing
Favicon
Working with streams in Node.js
Favicon
Migrating to Phoenix Liveview Streams
Favicon
What is Java Stream and why does it exist?
Favicon
-
Favicon
Streams em Node.js para iniciantes (guia básico)
Favicon
From a data stream to the data warehouse
Favicon
Gentle Intro to Node Streams
Favicon
The Java `.boxed()` Method
Favicon
Request and Response Stream - Observations
Favicon
Getting a near-real-time view of a DynamoDB stream with Python
Favicon
Exploring Java Streams
Favicon
Service Worker Side Rendering (SWSR)
Favicon
Listening to payments (real-time) on your Stellar wallet
Favicon
Supporting Cross Node Interactive Queries In Kafka Streams
Favicon
Summing Java Streams Api
Favicon
Handling Slow Servers in NodeJS
Favicon
Java 8 Non ce n’est pas que les streams

Featured ones: