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.
const records = new Readable({ objectMode: true, read() {} }); records.push({ id: 1 });
Try it
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.
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:
objectModesets both sides.readableObjectModeandwritableObjectModeset one side of aDuplexorTransform. - Chunks: every
push(value)orwrite(value)is one chunk. Strings stay strings (no encoding conversion). - Counting:
highWaterMarkis a number of objects, default 16, no matter how big each object is. See highWaterMark. - Special value:
nullstill means end of stream in a readable (push(null)). You cannot streamnull; use a wrapper object.undefinedis 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.stdoutfails unless the objects are strings or buffers. Serialize with aTransformfirst (for exampleJSON.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
highWaterMarkfor heavy records. - Operators such as
map(),filter()andtoArray()work best with object-mode or iterable-based streams.