how to log the file requested via express.static

前端 未结 3 1057
傲寒
傲寒 2021-02-07 04:51

here is my code

var express=require(\"express\");
var app=express();
var port=8181;
app.use(express.static(__dirname));
app.listen(port);

it i

3条回答
  •  深忆病人
    2021-02-07 05:18

    You want to log what serve-static (express.static) gives in response. There're several ways to do this.

    Method Ⅰ A middleware for manual checks.

    You may put (app.use) a middleware that logs a request if it's for express.static, before express.static. Rodrigo Medeiros' answer does this. But this way, you have to rewrite the code for checks when the options for the serve-static middleware changes, which might be a maintaining issue.

    Method Ⅱ Hooking into express.static; leaking info out of it.

    Well, express.static knows what files it gives best. It just, unfortunately, does not let us know and log it. But there's a hack for this: the setHeaders option, which is a callback function supposedly used to set custom response headers. It's called when express.static makes a response and gets enough information to log what you want to.

    const express = require("express");
    const path = require("path");
    const app = express();
    const asset_dir_path = "assets/";
    
    app.use(express.static(asset_dir_path, {
        index: false,
        setHeaders: (response, file_path, file_stats) => {
            // This function is called when “serve-static” makes a response.
            // Note that `file_path` is an absolute path.
    
            // Logging work
            const relative_path = path.join(asset_dir_path, path.relative(asset_dir_path, file_path));
            console.info(`@${Date.now()}`, "GAVE\t\t", relative_path);
        }
    }));
    

提交回复
热议问题