In Express.js, we can serve static files (such as CSS, images, or client-side Javascript) using the "express.static" middleware.
This middleware function is based on the serve-static module.
Express.js `express.static` middleware makes it easy to serve static files without writing custom code for each file type.
Express.js sets required caching headers by default, improving the loading speed of static assets by allowing browsers to cache them.
const express = require('express'); const app = express(); const path = require('path'); // Serve static files from the 'public' directory app.use(express.static('public')); // or use below syntax // app.use(express.static(path.join(__dirname, 'public')));
The `__dirname` is a global variable that provides the absolute path to the current directory containing the Javascript file (server.js).
Place your static files (e.g., CSS, images, JavaScript) inside the "public folder" directory.
Configure your Express app to use the "express.static" middleware to serve static files:
const express = require('express'); const app = express(); const path = require('path'); const PORT = 3000; // Serve static files from the 'public' directory app.use(express.static('public')); // express.static method is middleware // or use below syntax // app.use(express.static(path.join(__dirname, 'public'))); // Get Method app.get('/', (req, res) => { res.send('Hello, Express with static files!'); }); // Start the Express server on specific port app.listen(PORT, () => { console.log(`Server is running on port ${PORT}`); });
"express.static" middleware is added to the middleware stack using "app.use()".
It takes the name of the directory containing the static files as an argument. In this case, it's the public directory.
Now, any files in the public directory can be accessed directly from the browser. For example, if you have an image named "logo.png" in the public directory, you can access it at http://localhost:3000/logo.png.
Make sure to adjust the paths and directory structure according to your project's setup.
This is a common and effective way to organize and serve static assets in an Express.js application.
node server.js
Now, you can open a web browser and navigate to `http://localhost:3000/media-name.media-type` to view your static web page served by Express.js.
In Express.js, we can serve various types of static files such as HTML, CSS, Javascript, images, or other types of files.
Express.js provides a flexible and robust solution for handling static content without writing any extra code for file serving.
By organizing our static assets in a designated directory and utilizing the built-in static file-serving capabilities of Express.js, we can streamline the development process and enhance the performance of our web applications.