Skip to content
Tutorials Center
My learning

Topics

Node.js Reference ยท Streams and readline

Node.js stream object mode

Explains object mode in Node.js streams: pass JavaScript values instead of bytes, how highWaterMark counts objects, mixing modes in a Transform, and pitfalls.

Normally a stream moves bytes: Buffers and strings. Setting objectMode: true lets a stream carry any JavaScript value, one value per chunk. Records parsed from a CSV file, rows from a database, or parsed JSON messages all fit naturally, and chunks are never merged or split.

Object mode only affects the stream you create it on. In a pipeline, each stream decides its own mode, and a Transform can even read bytes and write objects.

NODE
const records = new Readable({ objectMode: true, read() {} });
records.push({ id: 1 });

Try it

Node.js Records through a pipeline

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Node.js Bytes in, objects out

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

How it works

  • Constructor options: objectMode sets both sides. readableObjectMode and writableObjectMode set one side of a Duplex or Transform.
  • Chunks: every push(value) or write(value) is one chunk. Strings stay strings (no encoding conversion).
  • Counting: highWaterMark is a number of objects, default 16, no matter how big each object is. See highWaterMark.
  • Special value: null still means end of stream in a readable (push(null)). You cannot stream null; use a wrapper object. undefined is allowed in a readable but is ambiguous in practice.

Usage notes

  • Readable.from(iterable) creates an object-mode stream by default. Pass { objectMode: false } for a byte stream from buffers or strings.
  • Byte streams and object streams do not mix freely: piping an object-mode readable into a byte writable such as process.stdout fails unless the objects are strings or buffers. Serialize with a Transform first (for example JSON.stringify(obj) + "\n").
  • Chunks keep their identity. If a consumer mutates an object, upstream stages hold the same reference.
  • The mode is fixed at construction. You cannot toggle it later.
  • Memory is not bounded by size: sixteen huge objects can still fill memory, so lower highWaterMark for heavy records.
  • Operators such as map(), filter() and toArray() work best with object-mode or iterable-based streams.