Node.js
HighWaterMark
Learn highWaterMark and the buffer limit.
What is highWaterMark?
highWaterMark is the ceiling for a stream's buffer. The stream buffers data until this threshold is crossed; past it, backpressure fires. Defaults are 64 KB for byte mode and 16 objects for object mode.
A bufferState(currentSize) function models this: if currentSize >= HIGH_WATER_MARK it returns 'paused', otherwise 'flowing'. HIGH_WATER_MARK is a constant, say 16. bufferState(8) returns 'flowing', bufferState(20) returns 'paused'. The ternary has the form condition ? true : false; it is shorthand for if/else. This model reduces highWaterMark to a single constant and yields deterministic output.
Flowing and paused
While the buffer is 'flowing', the stream actively pushes data to the consumer. When 'paused', it waits and hands data only when the consumer calls .read(). The two states pivot on highWaterMark.
Example: bufferState(8) returns 'flowing' because 8 < 16. bufferState(20) returns 'paused' because 20 >= 16. In a real Node.js stream this transition is handled by the 'drain' event; in our simple model the ternary shows it in one line. This way you can visualize highWaterMark's role through the size that crosses the threshold. Later, when you set the highWaterMark option on stream.Readable, this mental model will guide you.
Exercise Write the buffer state function
Define const HIGH_WATER_MARK = 16. Write function bufferState(currentSize) { return currentSize >= HIGH_WATER_MARK ? 'paused' : 'flowing'; }. Print console.log(bufferState(8)) and console.log(bufferState(20)).
Show example solution
const HIGH_WATER_MARK = 16;
function bufferState(currentSize) {
return currentSize >= HIGH_WATER_MARK ? 'paused' : 'flowing';
}
console.log(bufferState(8));
console.log(bufferState(20));
Test yourself
-
Complete the ternary expression
return currentSize >= HIGH_WATER_MARK ? '____' : 'flowing';
Show answer
return currentSize >= HIGH_WATER_MARK ? 'paused' : 'flowing';
-
Match each piece to its role
- HIGH_WATER_MARK
- Buffer ceiling
- flowing
- Actively pushes
- paused
- Waits
- ternary
- Conditional expression
-
What does bufferState(8) return when HIGH_WATER_MARK=16?
const HIGH_WATER_MARK = 16;
function bufferState(c) {
return c >= HIGH_WATER_MARK ? 'paused' : 'flowing';
}
bufferState(8)
Show answer
flowing — 8 < 16 so it returns 'flowing'.
Next lesson: Object mode