A
A
alex4answ2020-08-24 16:47:04
Node.js
alex4answ, 2020-08-24 16:47:04

Why is the Stream buffer not filling up?

Good afternoon, I'm studying streams, I just can't execute the "buffer is full, I need to clear" scenario in a Writable stream

, here's what I'm doing:

const { Writable } = require('stream');

class Counter extends Writable {
  _write(chunk, encoding, next) {
    console.log(chunk.toString());
    next();
  }
}

const counter = new Counter({ highWaterMark: 2 }); // Размер буффера 2 байта

for(let i = 0; i < 1000; i++) {
  const buffer     = Buffer.from(`${i}`, 'utf8');
  const canWrite = counter.write(buffer); // всегда true, даже пробовал рандомный текст вставлять
}


The documentation says:
Returns: false if the stream wishes for the calling code to wait for the 'drain' event to be emitted before continuing to write additional data; otherwise true.


The buffer is full, waiting to be cleared, but the write method always returns true, why, where did I go wrong?

UPD. I understand that by calling next() in the _write() method, I signal a successful data write and the buffer is cleared , am I right?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
R
Robur, 2020-08-25
@alex4answ

I understand that by calling next() in the _write() method, I signal a successful data write and the buffer is cleared, am I right?

Yes:
The callback function must be called synchronously inside of writable._write() or asynchronously (ie different tick) to signal either that the write completed successfully or failed with an error.

All calls to writable.write() that occur between the time writable._write() is called and the callback is called will cause the written data to be buffered.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question