Introduction to Readable-Stream
The readable-stream
module in Node.js is an essential component when working with stream-based data. It provides a set of APIs to handle reading and interacting with data streams efficiently. Whether you are dealing with file streams, HTTP requests, or any other type of stream, the readable-stream
module can significantly enhance your data processing tasks.
Key APIs in Readable-Stream
Creating a Readable Stream
To create a readable stream, you can use the Readable
class:
const { Readable } = require('readable-stream');
const readable = new Readable({
read(size) {
this.push('Hello, Stream!');
this.push(null);
}
});
readable.pipe(process.stdout);
Piping Data
Piping is a technique to pass data from one stream to another. It is commonly used for connecting readable streams to writable streams:
const { Readable, Writable } = require('readable-stream');
const readable = new Readable({
read() {
this.push('Stream data!');
this.push(null);
}
});
const writable = new Writable({
write(chunk, encoding, callback) {
console.log(chunk.toString());
callback();
}
});
readable.pipe(writable);
Handling Stream Events
Streams in Node.js emit several events like data
, end
, and error
. Here’s how you can handle these events:
const { Readable } = require('readable-stream');
const readable = new Readable({
read() {
this.push('Event-driven stream data!');
this.push(null);
}
});
readable.on('data', (chunk) => {
console.log('Received data:', chunk.toString());
});
readable.on('end', () => {
console.log('Stream ended.');
});
readable.on('error', (err) => {
console.error('Stream error:', err);
});
readable.pipe(process.stdout);
Sample Application Using Readable-Stream
Let’s create a simple application that reads data from a file, processes it, and writes the results to another file:
const fs = require('fs'); const { Transform } = require('readable-stream');
const readStream = fs.createReadStream('input.txt'); const writeStream = fs.createWriteStream('output.txt');
const transformStream = new Transform({
transform(chunk, encoding, callback) {
this.push(chunk.toString().toUpperCase());
callback();
}
});
readStream
.pipe(transformStream)
.pipe(writeStream)
.on('finish', () => {
console.log('Transformation complete. Check output.txt.');
});
Conclusion
The readable-stream
module in Node.js is a powerful tool for handling stream data. With the above examples and API explanations, you can optimize your data processing tasks and implement robust stream-based applications. Dive deeper into the module’s documentation to discover even more capabilities and advanced usages.
Hash: 88369504f3f6e71ea4c90744ee9194f6b241ba5f469cb3b517f83bc460bded34