HighWaterMark
- Node.js course
- Expert
- Lesson 26/47
- 5 min
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.
Practice 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)).
Starter code
// Define the ceiling constant as 16
// Write bufferState: return 'paused' or 'flowing' with a ternary
// Print calls with 8 and 20
// write hereSample solution
const HIGH_WATER_MARK = 16;
function bufferState(currentSize) {
return currentSize >= HIGH_WATER_MARK ? 'paused' : 'flowing';
}
console.log(bufferState(8));
console.log(bufferState(20));Expected output
flowing paused
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Complete the ternary expression
return currentSize >= HIGH_WATER_MARK ? '____' : 'flowing';
return currentSize >= HIGH_WATER_MARK ? 'paused' : 'flowing';
Explanation: Past the threshold it returns 'paused'.
2 Match each piece to its role
| Term | Meaning |
|---|---|
HIGH_WATER_MARK |
Buffer ceiling |
flowing |
Actively pushes |
paused |
Waits |
ternary |
Conditional expression |
3 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)- 8
- flowing Correct answer
- paused
- 16
Explanation: 8 < 16 so it returns 'flowing'.