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

Viewed 1122

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!

2 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));
const express = require('express');
const path = require('path');
const app = express();
app.use('/public',express.static(path.join(__dirname,'static')));
app.get('/',(req,res)=> {
          res.sendFile(path.join(__dirname,'static','index.html');
         });
app.listen(3000);
Related