JavaScript

Serving static files in Express.js

Hello in this tutorial, we will understand how to serve static files on an Express.js server. There are two ways to serve static files in express:

  • Serving a single file through the HTTP response by configuring the path to the resource
  • Serving multiple files from the public directory

In this tutorial, we will go over the recommended approach which is serving multiple files from the public directory named assets.

1. Introduction

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

Express.js static files - node and npm
Fig. 1: Verifying node and npm installation

2. Serving static files in Express.js

To set up the Express.js server, we will need to navigate a path where our project will reside. For programming stuff, I am using Visual Studio Code as my preferred IDE. You’re free to choose the IDE of your choice.

2.1 Setting up dependencies

Navigate to a directory and run npm init -y to create a package.json file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Add the following code to the file wherein we will specify the dependencies.

package.json

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
{
  "name": "expressjs-static-files",
  "version": "1.0.0",
  "description": "",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "node app.js"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.1"
  },
  "devDependencies": {
    "nodemon": "^2.0.7"
  }
}

To download the dependencies navigate to the directory path containing the file and use the npm install command. If everything goes well the dependencies will be loaded inside the node_modules folder and you are good to go with the further steps.

2.2 Creating an Express server

Add the following code to the app.js file and set the folder (named assets) containing the files. We will call app.use(…) method to use a middleware function in Express. express.static(…) method finds and returns the static files from the specified root directory.

app.js

01
02
03
04
05
06
07
08
09
10
11
12
// base setup
const express = require('express');
const app = express();
const port = 10091;
 
// setting up the public directory
app.use('/public', express.static('assets'));
 
// starting the server
app.listen(port, () => {
    console.log(`Application listening on port ${port}`)
});

2.3 Build a web page

Create an HTML file in the assets directory. Populate the file with HTML code and you are free to change the code as per your wish.

home.html

01
02
03
04
05
06
07
08
09
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE>
<html lang="en">
 
<head>
    <title>Index</title>
    <style>
        .nodejs {
            height: 250px;
            width: auto;
        }
    </style>
</head>
 
<body>
<h2>Hello world!<span>👋</span></h2>
<img alt="node" class="nodejs" src="./nodejs.jpg">
</body>
 
</html>

3. Run the Application

To launch the application navigate the project directory and enter the following command as shown in Fig. 2. If everything goes well the application will be started successfully on port number 10091.

Express.js static files - launch the app
Fig. 2: Launch the application

4. Project Demo

When the application is started, open the browser and navigate to http://localhost:10091/public/home.html. You will see the created HTML file.

Express.js static files - html page
Fig. 3: HTML page

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we learned:

  • Steps to setup Node.js
  • Sample programming to serve static files on an Express.js server

You can download the source code of this tutorial from the Downloads section.

6. Download the Project

This was a programming tutorial on serving static files on an Express.js server.

Download
You can download the full source code of this example here: Serving static files in Express.js

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button