在Node.js中,你可以使用中间件来记录请求处理时间。这里以Express框架为例,展示如何查看请求处理时间:
npm install express
app.js的文件,并在其中编写以下代码:const express = require('express');
const app = express();
// 自定义中间件,用于计算请求处理时间
app.use((req, res, next) => {
const start = Date.now(); // 记录请求开始时间
// 监听响应结束事件
res.on('finish', () => {
const duration = Date.now() - start; // 计算请求处理时间
console.log(`${req.method} ${req.url} - ${duration}ms`); // 输出请求方法、URL和处理时间
});
next(); // 调用下一个中间件
});
// 示例路由
app.get('/', (req, res) => {
res.send('Hello World!');
});
// 启动服务器
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
node app.js
现在,当你访问http://localhost:3000时,控制台将显示类似以下的输出:
GET / - 12ms
这表示请求处理时间为12毫秒。你可以根据需要修改中间件,以便在日志中包含更多信息或将其记录到文件中。