Serving static files
suggest changeWhen building a webserver with Express it’s often required to serve a combination of dynamic content and static files.
For example, you may have index.html and script.js which are static files kept in the file system.
It is common to use folder named ‘public’ to have static files. In this case the folder structure may look like:
project root
├── server.js
├── package.json
└── public
├── index.html
└── script.js
This is how to configure Express to serve static files:
const express = require('express');
const app = express();
app.use(express.static('public'));
Once the folder is configured, index.html, script.js, and the other files in public are available at the site root. Do not put /public/ in the URL. Express looks for files inside the folder you passed to express.static. A virtual prefix looks like this:
app.use('/static', express.static('public'));
will make the resources available under the /static/ prefix.
Multiple folders
It is possible to define multiple folders at the same time:
app.use(express.static('public'));
app.use(express.static('images'));
app.use(express.static('files'));
When serving the resources Express will examine the folder in definition order. In case of files with the same name, the one in the first matching folder will be served.