Readable and Writable Streams in Node.js

beginner
7 min

Readable and Writable Streams in Node.js

Welcome to our comprehensive guide on Readable and Writable Streams in Node.js! 🎯

By the end of this tutorial, you'll have a solid understanding of streams and how to use them in your projects. Let's dive in!

What are Streams?

Streams are Node.js objects that let you read data incrementally (Readable Streams) or write data incrementally (Writable Streams). They are crucial for handling large amounts of data efficiently, as they allow data to be processed in chunks instead of loading the entire data into memory at once. 💡

Readable Streams

Understanding Readable Streams

Readable Streams are used to read data from a source. In Node.js, a common example is reading from a file. 📝

javascript
const fs = require('fs'); const readableStream = fs.createReadStream('example.txt');

Reading Data from Readable Streams

To read data from a Readable Stream, we use the readableStream.on('data', callback) event. The callback function is invoked every time a chunk of data is available. 💡

javascript
readableStream.on('data', chunk => { console.log(chunk.toString()); });

Quiz

Quick Quiz
Question 1 of 1

Which Node.js object allows us to read data incrementally?


Writable Streams

Understanding Writable Streams

Writable Streams are used to write data to a destination. In Node.js, a common example is writing to a file. 📝

javascript
const fs = require('fs'); const writableStream = fs.createWriteStream('output.txt');

Writing Data to Writable Streams

To write data to a Writable Stream, we use the writableStream.write(chunk) method. 💡

javascript
writableStream.write('Hello, World!\n');

Finishing a Writable Stream

After writing all the data, we should call the writableStream.end() method to signal the end of the stream. 📝

javascript
writableStream.end();

Quiz

Quick Quiz
Question 1 of 1

Which Node.js method signals the end of a Writable Stream?


Combining Streams

Piping Streams

We can combine Readable and Writable Streams by piping (chaining) them together using the pipe() method. 💡

javascript
const fs = require('fs'); const readableStream = fs.createReadStream('example.txt'); const writableStream = fs.createWriteStream('output.txt'); readableStream.pipe(writableStream);

In the above example, data is read from example.txt and written to output.txt without storing it in memory.


By now, you should have a good understanding of Readable and Writable Streams in Node.js. Streams are essential for handling large amounts of data efficiently and are widely used in real-world projects. ✅

Happy coding! 🚀