Reputation: 820
I'm trying to serve up static files from two directories using express.
The reason I'm serving from two directories is due to naming collisions between the files being served in directory #1 having a matching directory name in directory #2
In directory #1, it will contain only files:
/path/to/dir1/foo (where 'foo' is a file)
In directory #2, it will contain sub-directories that contain files:
/path/to/dir2/foo/bar (where 'foo' is a dir && 'bar' is a file)
My objective is to be able to perform the following commands:
wget "http://myserver:9006/foo"
wget "http://myserver:9006/foo/bar"
The following snippet will accomplish everything up until directory #2 for me:
"use strict";
const express = require('express');
const app = express();
app.use('/', express.static('/path/to/dir1/'))
const server = app.listen(9006, () => {
let host = server.address().address;
let port = server.address().port;
console.log(`Example app listening at http://${host}:${port}`);
});
I'm trying to add the second static route with a regex to see if there is a '/' in the route so that I can direct it to directory #2. I'm thinking something along these lines, but haven't had any success:
app.use('/[^/]*([/].*)?', express.static('/path/to/dir2/'));
or
app.use('/.*/.*', express.static('/path/to/dir2/'));
I would appreciate any help.
Thanks in advance!
Upvotes: 1
Views: 451
Reputation: 3244
According to the docs, you can call express.static
multiple times and it will search for files in the order you specified the directories.
Folder Structure:
/
static/
s1/
foo # Contents: s1/foo the file
s2/
foo/
bar # Contents: s2/foo/bar the file.
The app is your exact code except for the two static lines:
const express = require('express')
const app = express()
app.use('/', express.static('static/s1'))
app.use('/', express.static('static/s2'))
const server = app.listen(9006, () => {
let host = server.address().address
let port = server.address().port
console.log(`Example app listening at http://${host}:${port}`)
})
And the pages work as expected
$ curl localhost:9006/foo
s1/foo the file
$ curl localhost:9006/foo/bar
s2/foo/bar the file.
Upvotes: 1