如何在express.js中获取上次请求的日期和时间 [英] How to get last request date and time in express.js
本文介绍了如何在express.js中获取上次请求的日期和时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想知道在服务器上发出最后一个请求时,我正在使用 expressjs
.
I want to know that when the last request has been made on server I am using expressjs
.
如何获取日期和时间?
推荐答案
我建议您使用 morgan
节点模块.此处的这段代码将所有请求记录到主目录中的 access.log
文件中.它还显示准确的时间和日期 请求.
I would suggest you to use morgan
node module. This code down here logs all the requests to access.log
file in the main directory. It also shows the exact time and dates request were made.
要将所有请求记录到文件
要做的事
- 下载模块
- 在目录中创建一个名为
access.log
的文件. -
运行代码
- Download the modules
- Create a file called
access.log
in the directory. Run the code
//modules
var express = require('express');
var fs = require('fs');
var morgan = require('morgan');
var path = require('path');
var app = express(); //set up the server
// create a write stream to the file
var accessLogStream = fs.createWriteStream(path.join(__dirname,
'access.log'), {flags: 'a'});
// setup the logger
app.use(morgan('combined', {stream: accessLogStream})); //streaming
//it to the file
app.get('/', function (req, res) {
res.send('Check the log file!')
})
app.listen(2222);
要仅获得最后一个请求,请使用此代码.发出请求时,它将获得日期和时间,然后将日期和时间记录到控制台.
To only get the last request use this code. It will get date and time when a request is made, then it will log the date and time to the console.
var express = require('express');
var app = express(); //set up the server
var readline = require('readline');
app.use(function(req, res, next){
var a = new Date().toLocaleString();
readline.cursorTo(process.stdout, 0);
process.stdout.write(a);
next();
});
app.get('/', function (req, res) {
res.send('Check the log file!');
})
app.listen(2222);
这篇关于如何在express.js中获取上次请求的日期和时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文