In this lesson, you will learn how to bypass the standard byte-by-byte buffer limitation of streams by transmitting structured JavaScript objects instead.
Beyond Raw Bytes
Up until now, we have treated streams as conduits for Buffer or string data. While this is perfect for files or network sockets, it forces you to manually serialize and deserialize complex data structures. If you are processing a stream of user records or JSON objects, constantly converting them to strings and back to objects becomes tedious and error-prone.
"Object Mode" solves this by allowing a stream to push and pull native JavaScript objects—like arrays, objects, or even class instances—directly through the pipeline.
Enabling Object Mode
To enable this, you simply pass the { objectMode: true } option when creating or extending a stream. This tells the internal stream mechanism to treat every chunk as a discrete item rather than a sequence of bytes.
Here is a quick look at a Transform stream that filters an object stream:
const { Transform } = require('stream');
const filterAdults = new Transform({
objectMode: true,
transform(user, encoding, callback) {
if (user.age >= 18) {
this.push(user); // Pass the raw object to the next stage
}
callback();
}
});
Why Use This?
When a stream is in object mode, the highWaterMark option no longer refers to the number of bytes stored in the buffer; it refers to the number of objects. This makes managing backpressure much more intuitive for high-level application logic. Instead of worrying about whether a chunk size is optimal for disk I/O, you focus entirely on your application's data flow.
Think of it as turning your data pipeline into a conveyor belt where, instead of loose sand (bytes), you are moving pre-assembled boxes (objects) directly to their destination. This approach reduces CPU overhead by eliminating unnecessary encoding/decoding and makes your streaming code significantly more readable.
Key Takeaway: Object mode allows streams to transport structured JavaScript objects instead of raw buffers, simplifying the processing of complex data pipelines.