Open In App

How to serve static files in Express JS ?

Last Updated : 04 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn how we can serve static files using Express. Static files are those files whose data are the same and whose content is constant and does not change, like a CSS file, images, or videos. Here we will use express.static middleware which helps to developer to send static file to client side.

Prerequisites

Approach

In this approach, we are going to use the built-in middleware of Express called express.static, which is used to server static files. This middleware will convert your root folder into an argument and return a function that you can use in your server-side application. Express.static is a built-in feature of Express JS , users do not need to install it separately. Path module is used in it to join the path from public directory to the required file.

Syntax:

app.use(express.static(path.join(__dirname, 'public')));

Steps to create application:

Step 1 : Make a root directory for server side code.

mkdir root

Step 2 : Initialize Node App using the given command.

npm init -y

Step 3 : Create entry point file and other required directories like public.

Step 4 : Install the required modules via given command.

npm i express

The updated dependencies in package.json file will look like:

"dependencies": {
    "express": "^4.18.2"
  }

Project Structure:

a

Example : This example uses express.static to serve a static CSS file to the Express server

Javascript




const express = require('express');
const path = require('path');
 
const app = express();
const PORT = 3000;
app.use(express.static(path.join(__dirname, 'public')));
 
app.get('/', (req, res) => {
    res.send('Hello Geek');
});
 
app.listen(PORT, () => {
    console.log(`Server Established at PORT->${PORT}`);
});


CSS




/* IT IS DEMO FILE */


Output:

Animation2



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads