const readableStream = fs.createReadStream('input.txt');const writableStream = fs.createWriteStream('output.txt');readableStream.pipe(writableStream); // Pipe data from input.txt to output.txt
3. Writable Streams
const fs = require('fs');const writableStream = fs.createWriteStream('output.txt');writableStream.write('This is the first line.\n');writableStream.write('This is the second line.\n');writableStream.end(); // No more data to writewritableStream.on('finish', () => { console.log('Finished writing data.');});writableStream.on('error', (err) => { console.error('Stream error:', err);});
4. Duplex Streams
const { Duplex } = require('stream');const duplexStream = new Duplex({ write(chunk, encoding, callback) { console.log(`Writing: ${chunk}`); callback(); }, read(size) { this.push('Data from read.'); this.push(null); // End the readable part }});duplexStream.write('Input data');duplexStream.on('data', (chunk) => console.log(`Read: ${chunk}`));
Backpressure means, when output stream target is not able to consume the stream, the read stream have to pause, so that there’s no memory leak. Otherwise it will keep queuing in the memory.