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

Why does listening to an event make a more accurate response time measurement in Express.js?

I’ve written an Express.js middleware to measure an endpoint’s response time that looks like this:

export function metricsMiddleware(req: Request, res: Response, next: NextFunction) {
  const startTime = Date.now();
  next();
  const durationMillis = Date.now() - startTime;
  console.log(durationMillis);
}

The values output are suspiciously low, in the range of sub-millisecond. I’m seeing an alternative approach to write it like:

export function metricsMiddleware(req: Request, res: Response, next: NextFunction) {
  const startTime = Date.now();
  res.on("finish", () => {
    const durationMillis = Date.now() - startTime;
    console.log(durationMillis);
  })
  next();
}

Why does the second approach work, while the first approach does not?

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

>Solution :

Because code executed by next() (which is whatever comes next after your middleware) may or may not be synchronous.

If everything after your middleware is synchronous (does not fetch anything from db etc) then it will be accurate.

But if you have anything asynchronous after the middleware then your console.log() will obviously execute befor next() is finished.

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