简体   繁体   中英

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:

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM