Search code examples
javascriptnode.jscallbackwebserverisolation

Node.js server request object seems not to be isolated when defined within a function


Consider this code:

const http = require("http")

const port = 8080

let myServer = http.createServer()
myServer.listen(port)

function serverSetOnFunctionAndDoRequest() {
  myServer.on("request",(req, res) => {
    res.writeHead(200)
    res.write("OK!")
    res.end()
  })
    
  http.get('http://localhost:' + port)
}

serverSetOnFunctionAndDoRequest()
serverSetOnFunctionAndDoRequest()
// Intentionally twice

I define a server and do two requests to it. The special thing here is that the myServer.on("request" event handler function is set within the function which does the request (serverSetOnFunctionAndDoRequest). For some reason, this is convenient for me to write a test. I had expected that each time I call the function another event handler callback would be registered and things would be isolated. However, the exact opposite seems to happen. I'll get ERR_STREAM_WRITE_AFTER_END Which does not occur if I put myServer.on("request" outside of serverSetOnFunctionAndDoRequest. The only explanation I have is that somehow the same res instance is used for both requests.

So, how come? And how can I solve this?


Solution

  • That's because any request can have only one response. If you register two event handlers, the first send a response, and that's what was expecting, the second response is unexpected and this is the reason you get that error.