node.jsexpressroutesstatic-files

Expressjs how to distribute static file loading depending on the path in the address bar


There is such a simple server

import express from "express";
import path from "path";
import fs from "fs";

const __dirname = path.resolve();
const app = express();

app.use(express.json());

app.use(express.static(path.join(__dirname, `src`), { index: 'none' }));///////////////

app.use(express.static(path.join(__dirname, `admin`), { index: 'none' }));////////////


app.get(`/*`, (req, res) => {
    let mainHtmlPath;
    if (req.url === '/admin') {  ///  // random error
        mainHtmlPath = path.join(__dirname, `admin`, 'index.html');
    } else {
        mainHtmlPath = path.join(__dirname, `src`, 'index.html');
    }

    fs.readFile(mainHtmlPath, 'utf8', (err, html) => {
        if (err) console.log(err, 'Ошибка')
        res.send(html)
    })
});


app.listen(80, () => console.log(`Server is run on port 80`))

I can't figure out how to make expressjs load the right static files

In the end, I need it to be like this

if the path starts with just /, so that static files are loaded only from the src folder especially since it can change, for example /user/setting/

and of course

if the path starts with just /admin, so that static files are loaded only from the admin folder especially since it can change, for example admin/users/list/

I don't know if I should give an example of my meager attempts

one of the variants of my attempts

app.use((req, res, next) => {
    console.log('++++++++++++++++++++++++++++++++++++++++++', req.url === '/admin/');
    console.log('++++++++++++++++++++++++++++++++++++++++++', req.url);
    if (req.url[0] === '/admin/') {
        express.static(path.join(__dirname, `admin`), { index: 'none' })
    } else {
        express.static(path.join(__dirname, `src`), { index: 'none' })
    }
    next()
})

I get this response in the console

but still, static files are not loading.


Solution

  • You can apply the static middleware on a specific path:

    app.use('/', express.static(path.join(__dirname, `src`), { index: 'none' }));
    // Here-^
    
    app.use('/admin', express.static(path.join(__dirname, `admin`), { index: 'none' }));
    // Here-^