Object mode
- Node.js course
- Expert
- Lesson 27/47
- 5 min
Learn the difference between stream object mode and binary mode.
What is object mode?
Streams default to binary mode: Buffer and string chunks flow. When object mode is on, each chunk is an object; this is useful for streaming numbers, arrays or records.
A chunkType(mode) function models the split: if mode === 'object' it returns 'object chunk', otherwise 'binary chunk'. In object mode highWaterMark counts objects, not bytes; this is why values like 16 objects are used. Object mode is turned on with new Readable({ objectMode: true }). Here we pin the split down with a single function; in a real stream the objectMode option makes the call.
The chunk type decision
A chunk's type depends on the stream's mode. In object mode a chunk is an object; in binary mode it is a Buffer or string. This split shapes how you handle data in _read and _write implementations.
Example: chunkType('object') returns 'object chunk'; chunkType('binary') returns 'binary chunk'. In object mode stream.read() returns an object; in binary mode it returns a Buffer. This simple function makes the link between mode and chunk type explicit. Later, when you write a Transform stream, setting objectMode is how you enforce this decision.
Practice Write the chunk type function
Write function chunkType(mode). Start with if (mode === 'object') return 'object chunk';. End with return 'binary chunk';. Print console.log(chunkType('object')) and console.log(chunkType('binary')).
Starter code
// Write the chunkType function
// Return 'object chunk' if mode is 'object', else 'binary chunk'
// Print calls with 'object' and 'binary'
// write hereSample solution
function chunkType(mode) {
if (mode === 'object') return 'object chunk';
return 'binary chunk';
}
console.log(chunkType('object'));
console.log(chunkType('binary'));Expected output
object chunk binary chunk
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match each piece to its role
| Term | Meaning |
|---|---|
Object mode |
Carries objects |
Binary mode |
Carries Buffers |
objectMode: true |
Option |
highWaterMark |
Threshold |
2 What does chunkType('object') return?
function chunkType(m) {
if (m === 'object') return 'object chunk';
return 'binary chunk';
}
chunkType('object')- binary chunk
- Buffer
- object chunk Correct answer
- undefined
Explanation: mode is 'object', so it returns 'object chunk'.
3 Complete the condition
if (mode === '____') return 'object chunk';
if (mode === 'object') return 'object chunk';
Explanation: mode is compared to 'object'.