Sometimes you want to serve files like images, styles, or scripts from different folders in your web app. Serving from multiple directories lets you organize files better and share them easily.
0
0
Serving from multiple directories in Express
Introduction
You have separate folders for images and CSS and want both accessible on your website.
You want to serve static files from a public folder and also from a shared library folder.
You are building a website with multiple sections, each with its own static files.
You want to add a third-party folder with assets without moving files.
You want to keep your app organized by separating static content into multiple places.
Syntax
Express
app.use(express.static('folder1')) app.use(express.static('folder2'))
Express checks the folders in the order you add them. It serves the first matching file it finds.
Use different folder names or paths to avoid conflicts between files with the same name.
Examples
This serves files from both 'public' and 'assets' folders. If a file is in both, the one in 'public' is served first.
Express
app.use(express.static('public')) app.use(express.static('assets'))
This serves images from 'img' folder under '/images' URL and CSS files from 'styles' folder under '/css' URL.
Express
app.use('/images', express.static('img')) app.use('/css', express.static('styles'))
Sample Program
This Express app serves static files from two folders: 'public' and 'shared'. Files in 'public' are checked first, then 'shared'.
For example, if you have 'public/index.html' and 'shared/logo.png', both can be accessed via the browser.
Express
import express from 'express' const app = express() const port = 3000 // Serve static files from 'public' folder app.use(express.static('public')) // Also serve static files from 'shared' folder app.use(express.static('shared')) app.listen(port, () => { console.log(`Server running at http://localhost:${port}`) })
OutputSuccess
Important Notes
Order matters: Express serves files from the first matching folder it finds.
You can use URL prefixes to separate folders, like app.use('/media', express.static('media'))
Make sure folder names and file names do not conflict to avoid confusion.
Summary
Serving from multiple directories helps organize static files better.
Use multiple app.use(express.static()) calls to add folders.
Express checks folders in order and serves the first matching file.