Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Node.js http module not closing the connection when no 'data' listener is set

Consider the following code:

const http = require('http')

const req = http.request({hostname: 'www.example.com'}, res=>{
  console.log('Response received')
  res.on('data',data=>{
    console.log('Received: '+data)
  })
  res.on('end',()=>{
    console.log('Connection ended')
  })
})
req.end()

As expected, it prints:

Response received
Received data
Connection ended

But when I remove the event listener for ‘data’, like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const http = require('http')

const req = http.request({hostname: 'www.example.com'}, res=>{
  console.log('Response received')
  res.on('end',()=>{
    console.log('Connection ended')
  })
})
req.end()

For some reason, it only prints:

Response received

Why is this? Does this mean the connection stays open?

Also, why does not setting an event listener even affect the behavior? Thanks in advance for any help.

>Solution :

Streams in node.js (which a HTTP Response is) start in "paused" mode. They wait for someone to read them, either through calls to read or by changing into "flowing" mode in which they continuously emit data events. Attaching an handler to the data event automatically sets them to flowing but since you never did this, the stream just waits, forever.

You can call res.resume() to set flowing mode without attaching an handler to the event. It’ll still read and emit data, but there’s nothing listening for that event so the data is just lost.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading