QA
Intermediate LevelNode JS

Why should you use stream.pipeline() over stream.pipe() for streaming file transformations?

❓ Interview Prompt: Compare `stream.pipe()` (swallows errors, potential memory leaks) vs `stream.pipeline()` (auto-cleans memory, handles errors, supports promises).

The Flaw with 'stream.pipe()':

If an error occurs mid-stream during '.pipe()', destination streams are NOT automatically closed or destroyed, causing memory leaks and open file descriptor leaks!

The Solution ('stream.pipeline()'):

'stream.pipeline()' safely forwards backpressure, handles errors across all stream stages, and automatically destroys all streams on failure!

Code Implementation Example

javascript
import { pipeline } from 'node:stream/promises';
import fs from 'node:fs';
import zlib from 'node:zlib';

async function compressFileSafely() {
  try {
    // Automatically destroys file handles on failure!
    await pipeline(
      fs.createReadStream('input.txt'),
      zlib.createGzip(),
      fs.createWriteStream('input.txt.gz')
    );
    console.log('Pipeline succeeded!');
  } catch (err) {
    console.error('Pipeline failed cleanly:', err);
  }
}
💡Safe stream transformation using stream.pipeline/promises.
🎯 Interview Key Takeaway

Always use stream.pipeline() instead of stream.pipe() to ensure streams are destroyed cleanly on error.

#pipeline#Streams#Backpressure#Error Handling#Intermediate
Back to all Node JS Questions→

More Node JS Interview Questions

Beginner LevelNode JS

How does the Node.js Event Loop work? Explain the 6 execution phases (Timers, Pending, Poll, Check, Close).

Beginner LevelNode JS

What does 'Single-Threaded, Event-Driven, Non-Blocking I/O' mean in Node.js?

Beginner LevelNode JS

What is the difference between process.nextTick() and setImmediate()?