Welcome back to CodeYourCraft! Today, we're diving deep into one of Node.js's powerful features - Streams. Let's get started!
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.
There are four types of streams in Node.js:
Let's create a simple readable stream by reading the contents of a file.
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.
Now, let's create a writable stream and write some data to a file.
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.
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! 🚀