Open In App

How To Serve Static Files in ExpressJS?

Last Updated : 27 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

ExpressJS is a popular web framework for NodeJS that allows developers to build robust web applications. One of its core functionalities is serving static files such as images, CSS, JavaScript, and HTML files.

Syntax

app.use(express.static(path.join(__dirname, 'public')));
  • Serves Static Files: This line makes ExpressJS serve static files (HTML, CSS, JS, images) from the public directory.
  • Constructs Path: It uses path.join() and __dirname to correctly build the absolute path to the public directory, ensuring compatibility across operating systems.

Steps ToServe Static Files

To set up an ExpressJS application, follow these structured steps:

Step 1: Create the Project Directory

Open your terminal and create a new directory for your project:

mkdir my-express-app
cd my-express-app

Step 2: Initialize the NodeJS Application

Initialize your project and create a package.json file:

npm init -y

Step 3: Install ExpressJS

Install ExpressJS as a dependency:

npm install express

Step 4: Set Up the Project Structure

Create the main application file and necessary directories:

touch app.js
mkdir public

Project Structure

Project Structure

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;
// Middleware to serve static files from 'public' directory
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}`);
});

In this Example

  • Express Setup: Initializes an ExpressJS application.
  • Static File Serving: Uses express.static() and path.join() to serve files (HTML, CSS, JS, images) from the public directory.
  • Root Route: Defines a route for the root path (/) that currently sends "Hello Geek". (This will be overridden if an index.html exists in the public directory.)
  • Port Listening: Starts the server and listens on port 3000.
  • Console Log: Logs a message to the console indicating the server has started.

Console Output

Consolelog
Console.log Output

Output:

serve static files in Express JS


Next Article

Similar Reads