I have as an assignment to do a nodeJS HTTP server with some form of metrics on it.
For this assignment, I am not allowed to use any form of external libraries & as the metric of the request I'll store the response time.
For route handling ill use a simple switch statement comparing the URL of the request
const http = require("http");
var metrics = []
http.createServer((req, res) => {
switch(req.url){
case "/route"
var start = Date.now();
// some code to process the request, maybe some requests to the database, maybe retrieve some files etc
res.end();
metrics.push(Date.now() - start);
break;
}
}).listen(8080,()=>console.log("Server running!"))
The thing is, if I want to do this app with one or a low number of requests this method would be ok, however, in any other normal scenarios, this would be awful for any further changes to those metrics & much more.
I'm thinking of trying to solve this with some sort of event listeners that I would call at the beginning & the end of my request. Something that would store information about the request at the beginning & launch an event at the end to stop processing the metrics.
server.on('end', (data)=>{
//end metrics somehow
})
Although it seems a little hard to implement, especially as I don't really want to overwrite a nodeJS event to add some data on it ( for instance I may want to add an id of the request, or a timestamp )
Is there a way to properly do this with nodeJS HTTP?
metrics, you could always put that before the switch statement. Honestly, all of this is easier with a stack like Express where we can use middleware. You could recreate that yourself in your own code... it isn't too complicated for the basics.