This tutorial aims to provide a comprehensive introduction to Streams and Buffers in Node.js. This is an important concept in Node.js as it allows efficient handling of data, particularly when dealing with large volumes of data.
By the end of this tutorial, you will:
Before we start, you should have:
In Node.js, a stream is an abstraction layer that handles reading/writing data in continuous chunks, instead of reading/writing the entire data at once. This allows efficient data handling, especially in cases of large data transfers.
There are four types of streams:
Buffers are a global object in Node.js used to store and manipulate binary data.
In Node.js, streams use buffers to temporarily hold data that's being transferred between places. The chunks of data are buffered until the destination is ready to process them.
const fs = require('fs');
// Create a readable stream
let readableStream = fs.createReadStream('input.txt');
// Handle stream events --> data, end, and error
readableStream.on('data', function(chunk) {
console.log(chunk);
});
readableStream.on('end', function() {
console.log('Reading Ended');
});
readableStream.on('error', function(err) {
console.log(err.stack);
});
In this example, we're creating a readable stream from a file named 'input.txt'. We then listen to various events like 'data', 'end', and 'error'. The 'data' event is emitted whenever the stream passes a chunk of data to the consumer.
const fs = require('fs');
// Create a writable stream
let writableStream = fs.createWriteStream('output.txt');
// Write data to stream with encoding to be utf8
writableStream.write('Hello World!\n', 'UTF8');
// Mark the end of file
writableStream.end();
// Handle stream events --> finish, and error
writableStream.on('finish', function() {
console.log('Write completed.');
});
writableStream.on('error', function(err){
console.log(err.stack);
});
In this example, we are writing 'Hello World!\n' to a file named 'output.txt' using a writable stream.
In this tutorial, we have learned about Streams and Buffers in Node.js. We've seen how they work and why they’re important for efficient data handling. We also went through some practical examples demonstrating how to use them.
Now that you have a basic understanding of Streams and Buffers, you can explore more complex scenarios, like chaining streams and handling stream errors.