Generate Server-Timing headers interactively by setting timers in NodeJS
Inpired by:
📊 View your server's metrics in @ChromeDevTools via Server Timing headers. Big thanks to longtime Firebug developer @sroussey for the patch! pic.twitter.com/OjDDIv0lLR
— Paul Irish (@paul_irish) February 7, 2017
npm install servertiming --save
var ServerTiming = require("servertiming");
var timing = new ServerTiming();
var queryTimer = timing.startTimer("Database Query");
// ... do something work-intensive
var timeInMS = queryTimer.stop();
// or; var timeInMS = timing.stopTimer("Database Query");
// you can also add metrics without the timer function
// the time value is always in milliseconds!
timing.addMetric("Image Processing", 12847)
// If an operation you are timing fails before the
// timer can be stopped, you can clear that timer
try {
timing.startTimer("Failed Operation");
throw new Error("The operation failed!");
timing.stopTimer("Failed Operation");
} catch (e) {
timing.clearTimer("Failed Operation");
}
// ... use the header string within your server framework or whatever
res.setHeader("Server-Timing", timing.generateHeader());
return res.send({whatever: "you want"});
// this will output:
// database-query; dur=122; desc="Database Query",image-processing; dur=12847; desc="Image Processing"
See the /example folder for a detailed express.js example!