Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node express change static folder on a user by user basis

Is it possible to do something like this with node and express middleware?

app.use('/',express.static('public'))

app.get('/public', function() {
  app.use('/',express.static('public'))
})
app.get('/public2', function() {
  app.use('/',express.static('public2'))
})

What i'm trying to accomplish is allowing users to have their own "public" directories to serve static files. the directory structure would be something like /user/< hash >

like image 250
squirreldev Avatar asked Oct 31 '22 06:10

squirreldev


1 Answers

Think I have a solution for you!

app.get('/:user', function(req, res, next) {
    app.use('/', express.static(path.join(__dirname, 'public/' + req.params.user)));
    res.send('');
});

To explain, imagine the two files at the paths:

/__dirname/public/user1/userdata.text

/__dirname/public/user2/userdata.text

By visiting the following two URLs:

http://localhost:3000/user1/userdata.txt

http://localhost:3000/user2/userdata.txt

You'd be requesting those two different files respectively. If the file doesn't exist, it throws a 404 like you'd expect!

Hope this helps.

like image 113
jonny Avatar answered Nov 14 '22 21:11

jonny