Course contentsShow
← JavaScript
Lesson 1559 of 2,72334. Streams and BuffersFree lesson

Stream Error Handling

Properly catching and handling errors in readable and writable streams.

Stream Error Handling

You'll learn how to catch and handle errors that occur during stream operations to prevent crashes and ensure robust data processing.

Why Error Handling Matters in Streams

Streams perform I/O operations that can fail in many ways: files might not exist, network connections might drop, or disk writes might fail. Without proper error handling, these failures will crash your Node.js application. Unlike simple function calls, streams are asynchronous and event-driven, so you need to explicitly listen for errors.

The 'error' Event

Both readable and writable streams emit an 'error' event when something goes wrong. If you don't attach a listener, Node.js will throw an uncaught exception and terminate your process.

const fs = require('fs');

// BAD: No error handler - will crash if file doesn't exist
const badStream = fs.createReadStream('nonexistent.txt');

// GOOD: Error handler prevents crash
const goodStream = fs.createReadStream('nonexistent.txt');
goodStream.on('error', (err) => {
  console.error('Stream error:', err.message);
  // Handle gracefully instead of crashing
});

Handling Errors in Both Directions

When piping or working with both readable and writable streams, handle errors on both:

const readable = fs.createReadStream('input.txt');
const writable = fs.createWriteStream('output.txt');

readable.on('error', (err) => {
  console.error('Read error:', err.message);
});

writable.on('error', (err) => {
  console.error('Write error:', err.message);
});

readable.pipe(writable);

Think of error handlers as safety nets beneath a tightrope walker—they catch problems before they become disasters.

Key Takeaway: Always attach an 'error' event listener to every stream you create to prevent uncaught exceptions and handle failures gracefully.