Performance: Stream types (Readable, Writable, Transform, Duplex)
This concept affects how efficiently data flows through a Node.js application, impacting memory usage and responsiveness during I/O operations.
Jump into concepts and practice - no test required
const fs = require('fs'); const readable = fs.createReadStream('largefile.txt'); readable.on('data', chunk => console.log(chunk.toString()));
const fs = require('fs'); const data = fs.readFileSync('largefile.txt'); console.log(data.toString());
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Synchronous file read | N/A | N/A | N/A | [X] Bad |
| Readable stream with chunked async read | N/A | N/A | N/A | [OK] Good |
| Separate readable and writable streams for transform | N/A | N/A | N/A | [!] OK |
| Transform stream for inline data modification | N/A | N/A | N/A | [OK] Good |
| Separate readable and writable streams for bidirectional | N/A | N/A | N/A | [!] OK |
| Duplex stream for bidirectional data | N/A | N/A | N/A | [OK] Good |
const { Transform } = require('stream');
const upperCase = new Transform({
transform(chunk, encoding, callback) {
this.push(chunk.toString().toUpperCase());
callback();
}
});
upperCase.on('data', data => console.log(data.toString()));
upperCase.write('hello');
upperCase.end();const { Duplex } = require('stream');
const duplex = new Duplex({
read(size) {
this.push('data');
},
write(chunk, encoding, callback) {
console.log(chunk.toString());
callback();
}
});
duplex.on('data', data => console.log('Received:', data.toString()));
duplex.write('hello');