Master Node.js From Scratch

Clear, interactive, and structured Node.js lessons designed for beginners and developers.

COURSE SYLLABUS
1. Introduction to Node.js
Introduction to Node.js What Is Node.js? Node.js Architecture Features of Node.js Node.js vs Browser JavaScript Node.js Use Cases
2. Installation and Setup
Installation Introduction LTS and Current Versions npm Setup Environment Setup Verify Installation Node.js REPL
3. Node.js Fundamentals
Fundamentals Introduction Running JavaScript Global Objects Process Object Command-Line Arguments Environment Variables
4. JavaScript Basics
JavaScript Basics Introduction Variables: var, let and const JavaScript Data Types Comparison and Logical Operators If, Else If, Else and Switch Loops and Iteration Functions and Arrow Functions JavaScript Array Methods
5. Node.js Modules
Modules Introduction CommonJS Modules ES Modules Export and Import Built-in Modules Creating Custom Modules Path Module OS Module
6. Working with JSON
JSON Introduction JSON Syntax JSON.stringify() JSON.parse() JSON Array of Objects JSON User Database
7. Node Package Manager
npm Introduction package.json Installing Packages Dependencies and DevDependencies npm Scripts Package Versions and Semantic Versioning npm init and Project Setup
8. File System
File System Introduction Reading Files Writing Files Appending Files Deleting Files Working with Directories
9. CLI Applications
CLI Applications Introduction Command-Line Input Task Manager Project Structure Reading todos.json Adding, Updating and Deleting Tasks Saving Tasks to JSON
10. Events and EventEmitter
Events Introduction EventEmitter Registering Events Emitting Events Removing Event Listeners Custom Events
11. Asynchronous Programming
Async Programming Introduction Callbacks Promises async and await setTimeout() and setInterval() Event Loop and Non-Blocking I/O
12. Native HTTP Module
HTTP Module Introduction Creating an HTTP Server Handling Requests Sending Responses HTTP Request Methods Status Codes and Headers Handling POST Request Body Parsing Incoming JSON Products JSON API
13. Express.js
Express.js Introduction Installing Express Creating an Express Server Request and Response Objects Route Parameters and Query Strings Serving Static Files
14. Express Middleware
Middleware Introduction Built-in Middleware Application-Level Middleware Router-Level Middleware Custom Middleware Error-Handling Middleware
15. REST API Development
REST API Introduction GET Endpoints POST Endpoints PUT and PATCH Endpoints DELETE Endpoints Request Validation and API Responses
16. Database Integration
Database Introduction MySQL Integration MongoDB Integration Database CRUD Operations Database Queries and Filtering Connection Management
17. Authentication and Authorization
Authentication Introduction Password Hashing User Registration User Login JWT Authentication Authorization and Protected Routes
18. Advanced Node.js
Advanced Node.js Introduction Error Handling Debugging Node.js Applications Streams Buffers Performance and Security

Static Files in Express.js

Learn how to serve HTML, CSS, JavaScript, images and other static assets using the built-in express.static() middleware in Express.js.

When a user opens a website, the browser needs more than text from the server. It may also need HTML pages, CSS stylesheets, JavaScript files, images and fonts. Express.js provides the express.static() middleware to make these files available to the browser.

For example, a website developed for CIIT Training Institute may contain a homepage, institute logo, stylesheet and browser-side JavaScript. We can keep these files inside a public directory and configure Express.js to serve them.

1. What Are Static Files?

Static files are files that the server delivers to the client without dynamically generating their contents for each request. They commonly include website assets such as HTML, CSS, JavaScript, images and fonts.

Examples of static files include:

File Type Example Purpose
HTML index.html Defines the webpage structure.
CSS style.css Defines colors, layout and styling.
JavaScript script.js Adds browser-side functionality.
Images logo.png Displays logos and pictures.
Fonts font.woff2 Provides custom typography.
Remember: Express.js uses express.static() to serve files from a directory. The directory is commonly named public, but you can choose another name.

2. Why Do We Use Static Files?

A website usually contains multiple resources. Instead of writing a separate route handler for every CSS file, image or JavaScript file, we can configure static middleware to serve files from a directory.

Requirement Static File Result
Display a webpage index.html Browser displays the HTML page.
Apply webpage styling style.css Browser applies the CSS rules.
Add button functionality script.js Browser executes the JavaScript.
Display an institute logo images/logo.png Browser displays the image.

3. Understanding express.static()

express.static() is built-in middleware provided by Express.js. It accepts a directory path and serves files from that directory when the browser requests their corresponding URLs.

Basic Syntax

JavaScript
app.use(express.static("public"));

Understanding the Code

Code Explanation
app Represents the Express application.
app.use() Registers middleware in the application.
express.static() Creates middleware for serving static files.
"public" Specifies the directory containing the files.
Important: The relative path "public" is resolved from the Node.js process's current working directory. For a predictable path relative to the current JavaScript file, you can use path.join(__dirname, "public") in a CommonJS project.

4. Project Folder Structure

Before serving static files, create a project folder with an app.js file and a public directory. Store the website assets inside that directory.

Folder Structure
my-express-app/
│
├── app.js
│
└── public/
    ├── index.html
    ├── style.css
    ├── script.js
    └── images/
        └── logo.png

In this structure, app.js configures the Express server, while the public directory contains the files that the server can serve.

5. How Does Static File Serving Work?

When the browser requests a static file, Express.js checks the configured static directory. If the requested file exists and can be served, Express sends it to the browser.

1. Browser

Requests /style.css.

↓
2. Express Server

Receives the HTTP request.

↓
3. Static Middleware

Looks for the file inside public.

↓
4. Response

Sends the requested file if it is available.

If the requested file is not found, the static middleware allows the request to continue through the remaining middleware and route handlers. If no handler responds, Express normally returns a 404 response.

6. First Program: Serving an HTML File

Let's create a simple Express.js server that serves an HTML page from the public directory.

Step 1: Install Express.js

Terminal
npm init -y
npm install express

Step 2: Create app.js

JavaScript
const express = require("express");

const app = express();

app.use(express.static("public"));

app.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});

Step 3: Create public/index.html

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Express Website</title>
</head>
<body>
    <h1>Welcome to CIIT Training Institute</h1>
    <p>This page is served using Express.js static middleware.</p>
</body>
</html>

Step 4: Run the Server

Terminal
node app.js

Expected Terminal Output

Output
Server running at http://localhost:3000

Step 5: Open the Browser

URL
http://localhost:3000/index.html

Expected Browser Output

Welcome to CIIT Training Institute

This page is served using Express.js static middleware.

Explanation: The static middleware searches the public directory for index.html and sends the file to the browser.

7. Serving CSS Files

We can serve CSS files from the same public directory to style our HTML page. The browser requests the CSS file separately using the URL specified in the HTML document.

Step 1: Create public/style.css

CSS
body {
    font-family: Arial, sans-serif;
    background-color: #f0f4f8;
    text-align: center;
    padding: 40px;
}

h1 {
    color: #0d6efd;
}

p {
    font-size: 18px;
}

Step 2: Link the CSS File

Add the following link inside the <head> element of public/index.html.

HTML
<link rel="stylesheet" href="/style.css">

Expected Result

  • The webpage background becomes light blue-gray.
  • The heading uses blue text.
  • The paragraph uses the configured font size.

Because public is configured as the static directory, the file public/style.css is available at /style.css.

8. Serving JavaScript Files

Express.js can also deliver JavaScript files that run in the browser. In this example, we add a button and display a message when the user clicks it.

Step 1: Create public/script.js

JavaScript
document.getElementById("myButton")
    .addEventListener("click", () => {
        alert("Welcome to CIIT Training Institute!");
    });

Step 2: Update public/index.html

HTML
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Static Files Example</title>
    <link rel="stylesheet" href="/style.css">
</head>
<body>
    <h1>Express.js Static Files</h1>

    <button id="myButton">Click Me</button>

    <script src="/script.js"></script>
</body>
</html>

Expected Result

Open http://localhost:3000/index.html and click the button. The browser displays the following alert:

Browser Alert
Welcome to CIIT Training Institute!
Remember: Express.js serves the script.js file. The JavaScript code inside that file executes in the browser, not on the Express server.

9. Serving Image Files

Images can also be stored inside the public directory. For example, an institute logo can be stored at public/images/logo.png.

Folder Structure

Folder Structure
public/
├── index.html
├── style.css
├── script.js
└── images/
    └── logo.png

Display the Image

Add the following HTML inside the body of public/index.html.

HTML
<img src="/images/logo.png"
     alt="CIIT Training Institute Logo"
     width="200">

Direct Image URL

URL
http://localhost:3000/images/logo.png

The browser can request the image directly because the public directory is configured with express.static().

10. Using a Virtual Path Prefix

Express.js allows us to serve files under a URL prefix. This prefix changes the public URL without requiring us to move the actual files into a different directory.

Example Code

JavaScript
app.use("/static", express.static("public"));

Here, the files inside public are available through the /static URL prefix.

Actual File Browser URL
public/index.html /static/index.html
public/style.css /static/style.css
public/script.js /static/script.js
public/images/logo.png /static/images/logo.png

Test URL

URL
http://localhost:3000/static/index.html
Important: When using the /static prefix, update the asset paths in your HTML accordingly. For example, the stylesheet URL would be /static/style.css.

11. Using an Absolute Directory Path

A relative path such as "public" depends on the current working directory of the Node.js process. In a CommonJS project, we can use Node.js's path module and __dirname to build a path relative to the current JavaScript file.

Example Code

JavaScript
const express = require("express");
const path = require("node:path");

const app = express();

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

app.listen(3000, () => {
    console.log("Server running at http://localhost:3000");
});

Understanding the Code

Code Explanation
require("node:path") Loads Node.js path utilities.
__dirname Provides the directory of the current CommonJS module.
path.join() Combines path segments into a directory path.
express.static() Serves files from the resolved directory.
Note: This example uses CommonJS syntax. In an ES module project, the current directory is resolved differently because __dirname is not available by default.

13. Practice Task

Create a small Express.js website for CIIT Training Institute. Your application should:

  • Serve an HTML homepage from the public directory.
  • Apply styling using a separate CSS file.
  • Display an institute logo.
  • Load a browser-side JavaScript file.
  • Serve all assets through a /static URL prefix.
Practice URL: http://localhost:3000/static/index.html

12. Important Points

  • Static files include HTML, CSS, JavaScript, images and fonts.
  • Use express.static() to serve files from a directory.
  • Use app.use() to register static middleware.
  • The directory name public is a convention, not a requirement.
  • A virtual path prefix can expose assets under a URL such as /static.
  • Use path.join(__dirname, "public") for a directory path relative to the current CommonJS file.
  • Browser-side JavaScript executes in the browser.
  • Never place passwords, private keys or sensitive configuration files in a publicly served directory.

Summary

In this lesson, we learned how to serve static files using Express.js. We configured express.static() to serve HTML, CSS, JavaScript and image files from a public directory. We also learned how to use a virtual path prefix and resolve a static directory using Node.js path utilities. Static middleware makes it easier to deliver website assets without writing a separate route for every file.