show log time every request in Express?

Viewed 3481

I've some problem in here. I don't know why this is happened. I put timestamps code with Moment.js library, not only with that library, recently i created manually for showing timestamps but when i send request, time not updated. I put datetime in my file route. But this is work in server file.

So for example

server.js

var express = require('express')
var app = express()
var moment = require('moment')

app.use(function(req, res, next){
  console.log(moment().format('HH:mm:ss') + ' From server.js') //Showing time now
  next();
  })

app.use('/', index)
app.listen(8001)

routes/index.js

var express = require('express')
var app = express()
var router = express.Router()
var moment = require('moment')
var timestamps = moment().format('HH:mm:ss')

router.get('/', function(req, res){
  console.log(timestamps + ' From routes/index.js')
})

module.exports = routes

And i begin test for my code for first time GET localhost:8001/

My system time showing 16:20:51

[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node ./bin/www`
16:20:51 From Server.js
16:20:51 From routes/index.js

And the second request my system time showing 16:22:52

[nodemon] 1.11.0
[nodemon] to restart at any time, enter `rs`
[nodemon] watching: *.*
[nodemon] starting `node ./bin/www`
16:22:52 From Server.js
16:20:51 From routes/index.js

Nah, the second request still get existing time log from first request, this is only happened in routes. But work with well in server.js

Is it happened because variable timestamps outside function? But when i running without variable, it's worked.

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

Why this is can be happened? Thanks

2 Answers
Related