Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodejs express dynamic static folder based on route

I need to be able to have multiple static (public) folders which I can achieve using the following:

app.use(express.static(path.join(__dirname, '/routes/mymod1/public'))); 
app.use(express.static(path.join(__dirname, '/routes/mymod2/public')));

This merges the 2 folders so they appear as one, but the problem with this is if I have the same filename in both folders, then the last file will win.

What I would like to do instead, is to dynamically route the static requests based on the requested route.

For example a static request to /mymod1/test.html would be directed to /mymod1/public/test.html and requests to mymod2/test.html would be directed to /mymod2/public/test.html

Is this possible ??

like image 398
crankshaft Avatar asked Apr 10 '26 19:04

crankshaft


1 Answers

When you use the express.static middleware it try to resolve the file (in mymod1) and send it back. If no file is found the next middleware is call and try to resolve in mymod2 so the only the first one should win.

If you want to add a route, you can precise it as first argument:

app.use('/mymod1', express.static('...'))
like image 121
user3739239 Avatar answered Apr 13 '26 07:04

user3739239



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!