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

Duplex Stream Options

Configuring allowHalfOpen, readableObjectMode, and writableObjectMode for duplex streams.

Duplex Stream Options

You'll learn how to fine-tune duplex stream behavior using three key configuration options.

When you create a duplex stream (one that can both read and write), Node.js provides options to control how the readable and writable sides interact and handle data. Three critical options let you customize this behavior:

The Three Key Options

allowHalfOpen

By default, when the writable side of a duplex stream ends, Node automatically ends the readable side too (and vice versa). Setting allowHalfOpen: true allows one side to close while the other remains open.

Think of it like a phone call: normally, when one person hangs up, the call ends for both. With allowHalfOpen, one person could "hang up" their microphone but still listen through the speaker.

const { Duplex } = require('stream');

const duplex = new Duplex({
  allowHalfOpen: true, // Sides can close independently
  read() {},
  write(chunk, encoding, callback) {
    callback();
  }
});

readableObjectMode and writableObjectMode

These let you configure object mode separately for each side. Maybe you want to read JavaScript objects but write strings, or vice versa:

const duplex = new Duplex({
  readableObjectMode: true,  // Emit objects when reading
  writableObjectMode: false, // Expect Buffer/string when writing
  read() {
    this.push({ data: 'example' });
  },
  write(chunk, encoding, callback) {
    // chunk is Buffer/string here
    callback();
  }
});

This flexibility is powerful when transforming data formats between input and output.

Key Takeaway: Use allowHalfOpen to control whether duplex sides close together, and readableObjectMode/writableObjectMode to set different data handling modes for each side independently.