Express.js: Simplifying Static Assets
In web development, static assets like HTML, CSS, images, and client-side JavaScript files play a vital role in building a website. Express.js simplifies the process of serving these static files using the express.static() middleware.
What is express.static()?
How to Use express.static():
const express = require('express');
const app = express();
// Specify the path to the directory containing static assets
app.use(express.static('public'));
// Other routes and middleware definitions...
app.listen(5000, () => {
console.log('Server is running on port 5000...');
});
In this example:
Recommended by LinkedIn
The public directory is where your static files are located.When a request is made for a static file (e.g., /styles.css), Express will automatically serve the corresponding file from the public directory.
<!-- Linking to a CSS file -->
<link rel="stylesheet" href="/styles.css">
<!-- Using an image -->
<img src="/images/logo.png" alt="Logo">
Benefits of express.static():
Now, with express.static(), serving static assets in your Express.js app becomes effortless and efficient!