here is my code
var express=require(\"express\");
var app=express();
var port=8181;
app.use(express.static(__dirname));
app.listen(port);
it i
You want to log what serve-static (express.static
) gives in response. There're several ways to do this.
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.
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);
}
}));