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
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')
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With