0

我有一个代码,它使用 nodejs 和 express 进行简单的 HTML 流式传输。第一个流发生在第 3 秒,第二个流发生在第 6 秒,最后一个流发生在第 9 秒。该代码启用了 Morgon log 以记录响应时间。通过 Morgon 记录的响应时间显示为 3 秒(记录第一个流响应时间)。在 Morgon 或 nodejs 或 express 中是否有办法在启用流式传输时获得完整的响应时间?非常感谢您的帮助。

var express = require("express");
var bodyParser = require('body-parser');
var utf8 = require('utf8');
var axios = require('axios');
var morgan = require('morgan')
var fs = require('fs')
var path = require('path')
var app = express();
var port = 3000;
app.use(bodyParser.urlencoded({ extended: false }));
var urlencodedParser = bodyParser.urlencoded({ extended: true })
app.use(function(req, res, next) {
        var decodedUrl = decodeURIComponent(req.originalUrl);
        req.originalUrl = decodedUrl;
    next();
});
var accessLogStream = fs.createWriteStream(path.join(__dirname, 'access.log'), { flags: 'a' })
app.use(morgan(':method :url :response-time'))
// respond with "hello world" when a GET request is made to the homepage
app.get("/test/*/id*", urlencodedParser, function (req, res) {

    let soapUIHeader = '<dummy></dummy>';
    setTimeout(function() {
        res.write('<div><p>Header........</p><div>');
        setTimeout(function body() {
            res.write('<div><p>Body........</p><div>');
            setTimeout(function footer() {
                res.write('<div><p>Footer........</p><div>');
                res.end();
            },3000)
        },3000);
    },3000)
});


app.listen(port, function() {
    console.log("server started in port " + port);
});

module.exports = app
4

1 回答 1

2

启用响应流时测量响应时间的最佳方法是使用中间件。以下是步骤:

在 express 请求的开头引入一个中间件函数 setReqBeginTime。此函数捕获请求的当前时间并存储为请求标头 (req.headers['reqBeginTime'] = currentTime;)。在快速请求的末尾添加另一个函数 logResponeEndTime。该函数获取请求的最终执行时间,减去reqBeginTime得到响应时间。

希望这可以帮助

let setReqBeginTime = (req, res, next) => {
	var currentTime = Date.now();
	req.headers['reqBeginTime'] = currentTime;
	next();
}

let logResponeEndTime = (req, res, next) => {
	var currentTime = Date.now();
	var reqBeginTime = req.headers['reqBeginTime'];
	var responseTime = currentTime - reqBeginTime;
	req.headers['respEndTime'] = responseTime;
	next();
}

app.get("/test/*/id*", setReqBeginTime(), urlencodedParser, function (req, res) {

    let soapUIHeader = '<dummy></dummy>';
    setTimeout(function() {
        res.write('<div><p>Header........</p><div>');
        setTimeout(function body() {
            res.write('<div><p>Body........</p><div>');
            setTimeout(function footer() {
                res.write('<div><p>Footer........</p><div>');
                res.end();
            },3000)
        },3000);
    },3000)
}, logResponeEndTime());

于 2019-06-19T20:34:22.233 回答