Why is the callback for `stream.write` not called in Object mode

37 views Asked by At

In this snippet, we create a passthrough stream and write 20 integers to it

const stream = require('stream');
const ps = new stream.PassThrough({objectMode: true});

for (let i = 0; i < 20; i++) {
    const writeable = ps.write(JSON.stringify({n: i}), () => {
        console.log('write', i);
    });
}

ps.on('error', (err) => {
    console.log('error', err);
});

I would expect the callback (console.log('write', i);) to be called once for each iteration of the loop for a total of 20 logs. In reality, it is only called 15 times:

write 0
write 1
write 2
write 3
write 4
write 5
write 6
write 7
write 8
write 9
write 10
write 11
write 12
write 13
write 14
write 15

Process finished with exit code 0


Why is that?

Additionally, If I change the transform stream to no not support object mode (i.e. {objectMode: false}), then all writes are competed. What is the inherent difference between the two that causes this discrepancy?

0

There are 0 answers