node icon indicating copy to clipboard operation
node copied to clipboard

ServerResponse writeHead to accept a callback and/or emit a "headers" event.

Open lukiano opened this issue 2 years ago • 1 comments

What is the problem this feature will solve?

Currently, there exist libraries like https://www.npmjs.com/package/on-headers to allow developers to know when the response headers are being sent on the socket. They work by overwriting the writeHead method on the response object because there is no other way to know.

It would be useful if Node.JS provided this feature by itself.

An example of when this is useful is when measuring latency between a received request and a response being sent back.

What is the feature you are proposing to solve the problem?

There are two features in my proposal:

  1. https://nodejs.org/api/http.html#responsewriteheadstatuscode-statusmessage-headers to accept a callback that will be called when the headers are flushed.
  2. To also emit a headers (TBD) event. I'm undecided if doing it when writeHead is called or when the headers are flushed. I lean towards the latter.

What alternatives have you considered?

The aforementioned package overwrites the writeHead method which is not ideal.

Polling the headersSent field even less so.

lukiano avatar Sep 15 '22 08:09 lukiano

The challenge here is that writeHead() is a very common operation. Performance of the common case is absolutely not allowed to regress.

Both options, optional callback or new event, add bookkeeping overhead. Option 1 is probably the least worst of the two but still not free.

An example of when this is useful is when measuring latency between a received request and a response being sent back.

Is your example functionally equivalent to this?

const server = http.createServer((req, res) => {
  const startTime = Date.now()
  // ...
  console.log("latency:", Date.now() - startTime)
  res.writeHead(200)
})

The aforementioned package overwrites the writeHead method which is not ideal.

Why not?

bnoordhuis avatar Sep 18 '22 09:09 bnoordhuis

I'll go ahead and close this. OP has had six months to reply.

bnoordhuis avatar Mar 19 '23 10:03 bnoordhuis