Node.js Streams:
---------------
Streams are the objects that facilitate you to read data from a source and
write data to a destination. There are four types of streams in Node.js:
Readable: This stream is used for read operations.
Writable: This stream is used for write operations.
Duplex: This stream can be used for both read and write operations.
Transform: It is type of duplex stream where the output is computed according to input.
Each type of stream is an Eventemitter instance and throws several events at different
times. Following are some commonly used events:
Data:This event is fired when there is data available to read.
End:This event is fired when there is no more data available to read.
Error: This event is fired when there is any error receiving or writing data.
Finish:This event is fired when all data has been flushed to underlying system.
For Readable stream we will use the events : data , end , error.
For Writable stream we will use the events : error , finish .
Here's a summary of Node.js Streams with details on their types and events:
### **Node.js Streams**
Streams in Node.js are objects that allow you to handle data that is being read from a source or written to a destination. They are especially useful for working with large files or data streams like network requests or real-time data, as they allow you to process data piece by piece, without loading everything into memory at once.
### **Types of Streams**
1. **Readable Streams**:
- Used for reading data.
- Examples: `fs.createReadStream()`, HTTP request objects.
- **Events**:
- `data`: Fired when there is data available to read.
- `end`: Fired when no more data is available to read.
- `error`: Fired when an error occurs during reading.
2. **Writable Streams**:
- Used for writing data.
- Examples: `fs.createWriteStream()`, HTTP response objects.
- **Events**:
- `error`: Fired when an error occurs during writing.
- `finish`: Fired when all data has been flushed to the underlying system.
3. **Duplex Streams**:
- Used for both reading and writing data.
- Examples: TCP sockets, `net.Socket`.
- Duplex streams are both readable and writable.
4. **Transform Streams**:
- A type of duplex stream where the output is computed based on the input.
- Examples: `zlib.createGzip()`, `crypto.createCipher()`.
- These streams can modify or transform the data as it is read or written.
### **Common Events in Streams**
- **`data`**: Triggered when there is data available to read from a readable stream.
- **`end`**: Triggered when the readable stream has finished reading data.
- **`error`**: Triggered if there is an error during reading or writing operations.
- **`finish`**: Triggered when all data has been written to a writable stream.
### **Example of a Readable Stream**
```javascript
const fs = require('fs');
// Create a readable stream from a file
const readableStream = fs.createReadStream('example.txt');
// Listen for 'data' event to read data
readableStream.on('data', (chunk) => {
console.log(`Received ${chunk.length} bytes of data.`);
console.log(chunk.toString());
});
// Listen for 'end' event when there is no more data
readableStream.on('end', () => {
console.log('No more data to read.');
});
// Handle errors
readableStream.on('error', (err) => {
console.error('An error occurred:', err.message);
});
```
### **Example of a Writable Stream**
```javascript
const fs = require('fs');
// Create a writable stream to a file
const writableStream = fs.createWriteStream('output.txt');
// Write some data
writableStream.write('Hello, world!\n');
writableStream.write('Writing more data...\n');
// Mark the end of file
writableStream.end('This is the end.');
// Listen for 'finish' event
writableStream.on('finish', () => {
console.log('All data has been written.');
});
// Handle errors
writableStream.on('error', (err) => {
console.error('An error occurred:', err.message);
});
```
### **Conclusion**
Streams are powerful tools in Node.js that enable efficient handling of data flows. Understanding and utilizing streams can greatly improve the performance and scalability of your Node.js applications, especially when dealing with large files or data-intensive operations.
Comments
Post a Comment