Yenmangu
Yenmangu

Reputation: 101

Serve an entire /directory using an express server

I have an express server, and I would like to provide route handling to manage an entire directory.

root
   /html
       /css
       /js
           /app.js
       /images
       /index.html
       /some-other.html
   /server.js
   

Do I need to serve every file individually using

app.get('/', (req, res) => {
    res.send(htmlPath + '/index.html');
});

and adjust it for each .html file I am serving, or can I assign the /path-to-file as a variable and concatenate the variable into the htmlPath.

Additionally, is the following correct syntax to define the path/directory name

var htmlPath = path.join(__dirname, "html/");
app.use(express.static("html"));
app.use(express.static(__dirname));
app.use(express.static(path.join(__dirname, "/html")));

I am relatively new and have been following various other questions and answers to get to where I am now.

Upvotes: 0

Views: 51

Answers (1)

Salamis
Salamis

Reputation: 21

according to SOLID principle and MCV structure, I suggest you to handle each part of your directory in an individual file.

 root
/app
  /statics
     /images
     /css
  /views
    /index.html 
    /some-other.html
  /routes
    /statics.js
    /views.js
    /index.js
  /app.js
/server.js

so with this structure you have a routes directory which handle all the routes. in the index.js(Routes) you send each request to the correct route file:

const staticsRouter = require('./statics');
const viewsRouter = require('./views');

module.exports = (app) => {
    app.use('/statics',staticsRouterr);
    app.use('/views',viewsRouter);    
}  
   

and in router files response to each request.

Upvotes: 1

Related Questions