Complete the code to create a middleware function that records the start time.
function responseTimeTracker(req, res, next) {
req.startTime = [1];
next();
}We use Date.now() to get the current timestamp in milliseconds.
Complete the code to calculate the response time in milliseconds after the response finishes.
function responseTimeTracker(req, res, next) {
req.startTime = Date.now();
res.on('finish', () => {
const duration = [1] - req.startTime;
console.log(`Response time: ${duration}ms`);
});
next();
}We use Date.now() again to get the current time when the response finishes, then subtract the start time.
Fix the error in the middleware to correctly log the response time in seconds with two decimals.
function responseTimeTracker(req, res, next) {
req.startTime = Date.now();
res.on('finish', () => {
const duration = (Date.now() - req.startTime) / [1];
console.log(`Response time: ${duration.toFixed(2)}s`);
});
next();
}Dividing by 1000 converts milliseconds to seconds.
Fill both blanks to create a middleware that adds a custom header with the response time in milliseconds.
function responseTimeTracker(req, res, next) {
req.startTime = Date.now();
res.on('[1]', () => {
const duration = Date.now() - req.startTime;
res.setHeader('[2]', duration + 'ms');
});
next();
}The 'finish' event fires when the response is done. The header 'X-Response-Time' is a common custom header name.
Fill all three blanks to create a complete Express app using the response time middleware and a simple route.
const express = require('express'); const app = express(); function responseTimeTracker(req, res, next) { req.startTime = Date.now(); res.on('[1]', () => { const duration = Date.now() - req.startTime; res.setHeader('[2]', duration + 'ms'); }); next(); } app.use([3]); app.get('/', (req, res) => { res.send('Hello World'); }); app.listen(3000);
The middleware listens to the 'finish' event, sets the 'X-Response-Time' header, and is used with app.use().