Describe a scenario where using a `PassThrough` stream would be beneficial. Explain your reasoning and provide a code example.
Node.js interview question for Advanced practice.
Answer
A PassThrough stream is beneficial when you need to inspect, monitor, or tap into a stream without altering the data flow between the original source and destination. Scenario: A common use case is monitoring the progress of a large file upload or download. You can pipe the source stream through a PassThrough stream and attach a 'data' listener to it to count the bytes passing through, all while the data continues to flow unimpeded to its final destination. Code Example: Here, we use a PassThrough stream to report the progress of copying a large file. javascript const { PassThrough, pipeline } = require('stream'); const fs = require('fs'); const progressMonitor = new PassThrough(); let bytesWritten = 0; progressMonitor.on('data', (chunk) = { bytesWritten += chunk.length; console.log(Progress: ${bytesWritten} bytes written...); }); pipeline( fs.createReadStream('largefile.txt'), progressMonitor, // Intercepts data to monitor progress fs.createWriteStream('output.txt'), (err) = { if (err) { console.error('Copy failed:', err); } else { console.log(Copy succeeded! Total bytes: ${bytesWritten}); } } ); In this example, the progressMonitor doesn't change the data. It just observes the chunks as they pass from the read stream to the write stream and updates a counter.
Explanation
PassThrough streams are a very simple type of Transform stream where the transform method simply passes the data through without modification.