Express.js Masterclass
The Professional Backend Framework01.Home02.Introduction03.Express vs Native Node04.Express Generator05.Request Object (req)06.Response Object (res)07.Advanced Routing08.URL Params & Query09.Body Parsing10.Template Engines (EJS)11.Serving Static Files12.Middleware Architecture13.Must-Have Middleware14.File Uploads (Multer)15.Custom Error Handling16.Cookies & Sessions17.User Auth (Passport)18.Database Integration19.Data Validation20.Socket.io in Express21.Security & Helmet
Serving Static Files
To serve static files such as images, CSS files, and JavaScript files, use theexpress.static built-in middleware function in Express.
1. Basic Usage
Pass the name of the directory from which you want to serve static assets. Conventionally, this folder is named public.
app.use(express.static('public'));Now, you can load the files that are in the public directory:
http://localhost:3000/images/logo.pnghttp://localhost:3000/css/style.csshttp://localhost:3000/js/app.js
2. Virtual Path Prefix
You can create a "virtual" path prefix (where the path does not actually exist in the file system) for files that are served by Express.
app.use('/static', express.static('public'));Now, you access the files with the /static prefix:
http://localhost:3000/static/images/logo.png
3. Using Absolute Paths
It is safer to use the absolute path of the directory you want to serve, especially if you run your node app from another directory.
const path = require('path');
app.use('/static', express.static(path.join(__dirname, 'public')));Tip: You can use
express.static multiple times if you want to serve files from multiple directories. Express will look for files in the order you defined the middleware.