A Buffer in Node.js streams temporarily stores chunks of data to help manage the flow between fast data producers and slower consumers. This prevents data loss or overload.
When the internal buffer hits the highWaterMark, the readable stream pauses reading from the source to prevent memory overload until some data is consumed and the buffer has space again.
stream.on('data', (chunk) => {
// create buffer here
});Buffer.from() is the recommended way to create a Buffer from existing data like a stream chunk. The new Buffer() constructor is deprecated, and Buffer.alloc() creates an empty buffer of a specified size.
The writable stream simulates slow writing with a 100ms delay per chunk. Backpressure causes the readable stream to wait, so chunks print in order with delays.
If a readable stream pipes into a transform stream but the transform stream's output is not consumed (no pipe or data listener), the internal buffers fill up, causing a memory leak.