myHotTake

Tag: Writable stream

  • How Do Node.js Streams Work? A Simple Guide with Examples

    Hey there! If you enjoy this tale and find it helpful, feel free to give it a like or share it with friends who love a good story.


    Once upon a time, in the land of Soundwaves, I found myself in an enchanted forest where magical rivers flowed. These rivers weren’t ordinary; they were streams of music, each with its own unique rhythm and purpose. As I wandered, I encountered four distinct types of streams: the Readable, the Writable, the Duplex, and the Transform.

    First, I stumbled upon the Readable Stream. It was like a gentle river flowing from the mountains, carrying melodies downstream. I could sit by its banks and listen to the music it brought, but I couldn’t add anything to it. It reminded me of my favorite playlist, where I could enjoy song after song but had no way to alter the tunes.

    Next, I came across the Writable Stream. This was a river that invited me to contribute my own sounds. I could throw in my melodies, and they would flow downstream, joining the larger symphony. It felt like a blank music sheet where I could write my own notes, contributing to the world’s musical tapestry.

    As I ventured deeper, I met the Duplex Stream, a unique stream that flowed in both directions. It was like an interactive jam session where I could listen to the music coming from the mountains and simultaneously add my own harmonies. It was the best of both worlds, allowing for an exchange of creative energies as I both contributed to and received from the musical flow.

    Finally, I encountered the Transform Stream, the most enchanting of them all. This stream had the ability to take the melodies I contributed and magically transform them into something entirely new. It was like a magical remix station that could take a simple tune and turn it into a full-blown symphony. It felt like playing with a magical instrument that not only played my notes but also enhanced them, creating a masterpiece.

    As I left the forest, I realized that these streams were like the backbone of the Soundwaves world, each serving its own purpose and allowing for a seamless flow of music and creativity. If you enjoyed this journey through the magical forest of streams, feel free to share it with others who might appreciate the magic of Soundwaves too!


    1. Readable Streams

    In JavaScript, a Readable Stream is like that gentle river of melodies. It allows us to read data from a source. Here’s a simple example:

    const fs = require('fs');
    
    const readableStream = fs.createReadStream('music.txt', { encoding: 'utf8' });
    
    readableStream.on('data', (chunk) => {
      console.log('Listening to:', chunk);
    });

    This code snippet reads data from music.txt and lets us listen to the data as it flows.

    2. Writable Streams

    Writable Streams allow us to contribute our own melodies. We can write data to a destination:

    const writableStream = fs.createWriteStream('myTunes.txt');
    
    writableStream.write('My first melody\n');
    writableStream.end('The final chord');

    Here, we’re writing our own musical notes to myTunes.txt.

    3. Duplex Streams

    Duplex Streams let us both listen and contribute, just like our interactive jam session:

    const { Duplex } = require('stream');
    
    const duplexStream = new Duplex({
      read(size) {
        this.push('Listening to the beat\n');
        this.push(null);
      },
      write(chunk, encoding, callback) {
        console.log('Adding to the beat:', chunk.toString());
        callback();
      }
    });
    
    duplexStream.on('data', (chunk) => console.log(chunk.toString()));
    duplexStream.write('My rhythm\n');

    This duplex stream can both read and write data, allowing for a flow of music in both directions.

    4. Transform Streams

    Finally, Transform Streams take our melodies and remix them into something new:

    const { Transform } = require('stream');
    
    const transformStream = new Transform({
      transform(chunk, encoding, callback) {
        this.push(chunk.toString().toUpperCase());
        callback();
      }
    });
    
    transformStream.on('data', (chunk) => console.log('Transformed melody:', chunk.toString()));
    
    transformStream.write('soft melody\n');
    transformStream.end('gentle harmony');

    This transform stream takes input data, transforms it to uppercase, and outputs the new symphony.

    Key Takeaways

    • Readable Streams are for consuming data, much like listening to music.
    • Writable Streams let us write or contribute data, akin to composing music.
    • Duplex Streams allow simultaneous reading and writing, like an interactive jam session.
    • Transform Streams modify data during the flow, similar to remixing a tune.