检查用户是否在 Express 中打开了静态文件?

Zee*_*Zee 5 http node.js express

我正在使用以下方法提供静态文件:

app.use(express.static('static'));
Run Code Online (Sandbox Code Playgroud)

我有一个 index.html 和一堆其他文件./static/,它们显示在http://localhost:8080.

有什么方法可以拦截 GET 请求并确定用户何时打开了静态文件?我试过

app.get('/', (req, res) => { console.log("Opened!") }
Run Code Online (Sandbox Code Playgroud)

但这不起作用。

jon*_*nny 5

编辑:谢谢@robertklep 对我的解决方案的重构,它很好地概括了整个事情。下面是一个更简洁的解决方案,它会在提供任何静态文件时通知您,并打印其 URL:

const express = require("express");
const app = express();

const static = express.static('static');

app.use(function(req, res, next) {
    // declare a handler for the "request end" event
    function staticReqNotifier() {
        console.log("static file was served", req.url);
    }

    // listen to that event in before the static middleware is invoked
    req.on("end", staticReqNotifier);

    // manually invoke the static middleware with this middleware's arguments
    // we define the static middleware's next function - if it's called, the 
    // resource requested is not static so detach the listener and forward the response
    static(req, res, (err) => {
        req.off("end", staticReqNotifier);
        next(err);
    });
});

// test endpoint so show non-static requests work fine
app.get("/", function(req, res) {
    res.send("test");
});

app.listen(3000);
Run Code Online (Sandbox Code Playgroud)

由于任何快速请求最多只能由一个中间件来满足,因此在静态中间件之前侦听“请求已结束”事件,并在确定静态中间件尚未满足请求后将其分离就足够了。希望这可以帮助!