readable-stream icon indicating copy to clipboard operation
readable-stream copied to clipboard

Premature close error on socket under Node.js 12

Open vweevers opened this issue 2 years ago • 2 comments

This only happens with readable-stream@4 and Node.js 12. Later versions of Node, or earlier versions of readable-stream, work fine.

'use strict'

const net = require('net')
const { pipeline, PassThrough } = require('readable-stream')

const server = net.createServer(function (sock) {
  pipeline(sock, new PassThrough(), sock, function () { })
})

server.listen(3000, function () {
  const sock = net.connect(3000)

  // Change to false to avoid error
  if (true) {
    pipeline(sock, new PassThrough(), sock, (err) => {
      // NodeError: Premature close
      if (err) throw err
    })
  } else {
    sock.on('connect', function () {
      console.log('client connected')

      pipeline(sock, new PassThrough(), sock, (err) => {
        if (err) throw err
      })
    })
  }
})

vweevers avatar Jul 02 '22 11:07 vweevers

Happens because sock.readable is initially false (before connect has been emitted) and this branch is hit:

https://github.com/nodejs/readable-stream/blob/49a45a92f4ccacd6ab496c5b5143b117bea2fa8b/lib/internal/streams/end-of-stream.js#L192-L197

Which evaluates to:

if (
  !false &&
  (!false || true) &&
  (false || false === false)
) {
  process.nextTick(onclose)
}

vweevers avatar Jul 02 '22 12:07 vweevers

I'm not sure what can we do about this.

mcollina avatar Jul 02 '22 15:07 mcollina