0
0
Expressframework~5 mins

express.static middleware

Choose your learning style9 modes available
Introduction
express.static middleware helps your Express app serve files like images, CSS, and JavaScript easily to users without extra code.
You want to show images or styles on your website.
You need to serve JavaScript files for your frontend.
You want to share downloadable files like PDFs or documents.
You want to serve a whole folder of public files quickly.
You want to keep your server code clean by letting Express handle static files.
Syntax
Express
app.use(express.static('folderName'))
Replace 'folderName' with the folder where your static files are stored.
This middleware makes files inside the folder accessible via URL paths matching their names.
Examples
Serves all files inside the 'public' folder at the root URL.
Express
app.use(express.static('public'))
Serves files from 'assets' folder but URLs start with '/static'. For example, '/static/image.png'.
Express
app.use('/static', express.static('assets'))
Uses an absolute path to serve files from 'files' folder in your project, accessible under '/files' URL path.
Express
app.use('/files', express.static(path.join(__dirname, 'files')))
Sample Program
This Express app serves files from the 'public' folder. When you visit '/', it shows a welcome message and an image loaded from 'public/logo.png'.
Express
import express from 'express';
import path from 'path';

const app = express();
const PORT = 3000;

// Serve static files from 'public' folder
app.use(express.static('public'));

app.get('/', (req, res) => {
  res.send('<h1>Welcome!</h1><img src="/logo.png" alt="Logo">');
});

app.listen(PORT, () => {
  console.log(`Server running on http://localhost:${PORT}`);
});
OutputSuccess
Important Notes
Make sure the folder you serve exists and contains the files you want users to access.
Static middleware should be added before routes that might conflict with static file paths.
You can serve multiple static folders by calling app.use(express.static()) multiple times.
Summary
express.static middleware makes serving files like images and CSS easy.
It maps a folder to URLs so users can access files directly.
Use it to keep your server code simple and organized.