how to log the file requested via express.static

前端 未结 3 1058
傲寒
傲寒 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:05

    Just do

    var express=require("express");
    var app=express();
    var port=8181;
    
    app.use(function(req, res, next) {
        // check for .xls extension
        console.log(req.originalUrl);
        next();
    }, express.static(__dirname));
    
    app.listen(port);
    
    0 讨论(0)
  • 2021-02-07 05:16

    The path core module gives you the tools to deal with this. So, just put this logic in a middleware before your static middleware, like:

    var express = require("express");
    var path = require("path");
    
    var app = express();
    var port = 8181;
    
    app.use(function (req, res, next) {
        var filename = path.basename(req.url);
        var extension = path.extname(filename);
        if (extension === '.css')
            console.log("The file " + filename + " was requested.");
        next();
    });
    app.use(express.static(__dirname));
    
    app.listen(port);
    
    0 讨论(0)
  • 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);
        }
    }));
    
    0 讨论(0)
提交回复
热议问题