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.
CodePudding user response:
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.