show log time every request in Express? show log time every request in Express? express express

show log time every request in Express?


You cache the timestamp value.

Modify your route file this way:

var express = require('express')var app = express()var router = express.Router()var moment = require('moment')router.get('/', function(req, res){  var timestamps = moment().format('HH:mm:ss')  console.log(timestamps + ' From routes/index.js')})module.exports = routes

You have to understand that file is included once the application started and until it is running. The only part is called from time to time here is the function handler of the route:

function(req, res){  var timestamps = moment().format('HH:mm:ss')  console.log(timestamps + ' From routes/index.js')}


You were on right track! It is because you define timestamps outside the middleware*. The middleware is the function you register to the route and it gets called on each request that matches the specified url. So when you invoke moment() inside the middleware it returns the actual date and time of the request, since this function is executed only during the procession of a request. While in your case the code with the timestamps defined outside the function is executed only once - at the startup of the application when you require routes/index.js. But you may still use variable, just define it on the right place:

var express = require('express')var app = express()var router = express.Router()var moment = require('moment')var format = 'HH:mm:ss';router.get('/', function(req, res){  var timestamps = moment().format(format)  console.log(timestamps + ' From routes/index.js')})module.exports = routes