Streams in Node.js 🎯

beginner
18 min

Streams in Node.js 🎯

Welcome back to CodeYourCraft! Today, we're diving deep into one of Node.js's powerful features - Streams. Let's get started!

What are Streams? 📝

Streams are Node.js's way of handling continuous data streams (like reading a file line by line, streaming videos, etc.). They are a fundamental concept when it comes to I/O operations in Node.js.

Understanding Stream Types 💡

There are four types of streams in Node.js:

  1. Readable Streams: Used for reading data.
  2. Writable Streams: Used for writing data.
  3. Duplex Streams: Both readable and writable.
  4. Transform Streams: Reads data, transforms it, and writes the transformed data.

Creating a Readable Stream ✅

Let's create a simple readable stream by reading the contents of a file.

javascript
const fs = require('fs'); const stream = fs.createReadStream('example.txt'); stream.on('data', (chunk) => { console.log(chunk.toString()); });

In this example, we're creating a readable stream stream from the file example.txt. The data event triggers when data is available, and we're logging the data to the console.

Creating a Writable Stream ✅

Now, let's create a writable stream and write some data to a file.

javascript
const fs = require('fs'); const stream = fs.createWriteStream('output.txt'); stream.write('Hello, Node.js!'); stream.end();

In this example, we're creating a writable stream stream to write the string 'Hello, Node.js!' to the file output.txt. After writing the data, we're ending the stream to signal that no more data will be written.

Challenge 🎯

Quick Quiz
Question 1 of 1

What are the four types of streams in Node.js?

Stay tuned for more on Streams in Node.js! In the next lesson, we'll dive deeper into readable and writable streams and learn how to handle errors. See you then! 🚀