Bird
0
0

You want to log request time using functional middleware and then pass control. Which code correctly measures and logs the time taken by the next middleware or handler?

hard📝 Application Q9 of 15
NestJS - Middleware
You want to log request time using functional middleware and then pass control. Which code correctly measures and logs the time taken by the next middleware or handler?
Afunction timer(req, res, next) { console.log('Timer started'); }
Bfunction timer(req, res, next) { const start = Date.now(); console.log(`Time: ${Date.now() - start}ms`); next(); }
Cfunction timer(req, res, next) { const start = Date.now(); next(); const end = Date.now(); console.log(`Time: ${end - start}ms`); }
Dfunction timer(req, res, next) { next(); console.log('Timer started'); }
Step-by-Step Solution
Solution:
  1. Step 1: Measure time before and after next()

    Start time is recorded before calling next(), end time after next() returns.
  2. Step 2: Calculate and log elapsed time

    Subtract start from end to get duration, then log it.
  3. Final Answer:

    function timer(req, res, next) { const start = Date.now(); next(); const end = Date.now(); console.log(`Time: ${end - start}ms`); } -> Option C
  4. Quick Check:

    Log time after next() returns [OK]
Quick Trick: Record start before next(), log after next() [OK]
Common Mistakes:
  • Logging time before calling next()
  • Not calling next() at all
  • Logging static messages without timing

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More NestJS Quizzes