The express.static() is a built-in middleware function in Express.js that allows you to serve static files (like images, HTML, CSS, and JavaScript) directly to the client. It automatically makes all files inside a specified folder accessible via HTTP requests. You don’t have to create custom routes for each file.

Syntax
app.use(express.static('directory_name'));- directory_name: The path to the folder containing the static files (e.g., 'public', 'assets').
Code implementation of express.static()
Here are the steps:
Step 1: Create a public Folder
First, create a folder named public in your project directory. Inside this folder, place an index.html file and any images you want to display.

Step 2: Make a server.js file
Create a server.js file and add the following code to serve static files from the public folder.
//server.js
const express = require('express');
const app = express();
// Use express.static middleware to serve static files from the "public" folder
app.use(express.static('public'));
// Define a route (this is optional)
app.get('/', (req, res) => {
res.send('Welcome to my static website!');
});
// Start the server
const PORT = process.env.PORT || 3000;
app.listen(PORT, () => {
console.log(`Server is running on port ${PORT}`);
});
Step 3: Run the server
Use the following command to run the server.js file in your current working directory of the project
node server.jsStep 4: Open Your Browser
Visit the localhost:3000 to see the image that has been rendered on the page

Working of express.static()
- express.static is a built-in middleware function in Express that serves static files.
- It takes a directory path as an argument, indicating where static assets (like images, CSS, and JavaScript) are stored.
- When a request is made for a specific file, Express searches the specified directory for the file.
- If the requested file exists, Express sends it directly to the client (browser) with the appropriate content type.
- If the file is not found, Express returns a 404 error, indicating the resource is not available.
Use of express.static() function
- Serve Static Files: It serves static assets like HTML, CSS, JavaScript, and image files from a specified directory.
- Improved Performance: Express handles caching and optimized delivery of static content to improve load times.
- Simplified Routing: It eliminates the need for manually creating routes for each static file, making code cleaner.
- Organize Static Assets: It allows you to keep all static files in one directory, improving file management.
- Efficient File Delivery: It automatically serves files with the correct content type, making it easy to work with different file formats.