Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to serve static files in ExpressJS on some paths and not others

How can I serve static files with ExpressJS only from some of paths, while not for others?

To be more specific, I want to serve static files from all paths except /files (in case of request to this path, I want only to edit some file on the server).

I have this piece of code:

var express = require('express');
var app = express();
    
express.static(__dirname);
app.use(redirectUnmatched); 
function redirectUnmatched(req, res) {
    //Do something on server
    console.log("req.url:"+req.url+"<br>"+__dirname);
}
    
let port = 80;
var server = app.listen(port);

But I really don't know, how to edit my code to do that... Can anyone help me?

Thanks!

like image 244
Petr Marek Avatar asked Oct 17 '25 06:10

Petr Marek


1 Answers

Just defining the /files route before serving the static files might work:

// Define `/files` route first
app.use("/files", function (req, res) {
  return res.send("I will be served instead of a files directory");
});

// Static
app.use("/", express.static(__dirname));
like image 158
Dan Avatar answered Oct 19 '25 20:10

Dan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!