Node.js / Node.js HTTP and Web Servers

Serving Static Files in Node.js

This tutorial will teach you how to serve static files in Node.js. Static files, such as HTML, CSS, and JavaScript files, are a crucial part of any web application and need to be …

Tutorial 4 of 5 5 resources in this section

Section overview

5 resources

Explores building web servers and handling HTTP requests with Node.js.

Serving Static Files in Node.js

1. Introduction

Goal of the Tutorial

In this tutorial, we will learn how to serve static files such as HTML, CSS, and JavaScript using Node.js. These files are essential for any web application and must be delivered to the client efficiently.

Learning Outcomes

By the end of this tutorial, you will:

  • Understand how to serve static files in Node.js.
  • Be able to set up a server using the Express.js framework to serve static files.

Prerequisites

To follow this tutorial, you should have:

  • Basic knowledge of JavaScript.
  • Node.js and npm (Node package manager) installed on your computer.
  • Some familiarity with Express.js would be beneficial but is not necessary.

2. Step-by-Step Guide

To serve static files in Node.js, we will use the Express.js framework, a fast, unopinionated, and flexible Node.js web application framework. Express provides a built-in middleware function, express.static, to serve static files.

Installing Express

First, you need to install Express. In your project directory, run the following command:

npm install express

This will install Express in your project and add it to your package.json file's dependencies.

Serving Static Files

To serve static files such as images, CSS files, and JavaScript files, use the express.static built-in middleware function in Express.

Here's a basic example:

const express = require('express');
const app = express();

// Serve static files from the "public" directory
app.use(express.static('public'));

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

In this code, express.static('public') serves static assets from the public directory. If you put a file named style.css in the public directory, you can access it at http://localhost:3000/style.css.

3. Code Examples

Example 1: Serving an HTML file

Create a directory named public and put a file named index.html in it. Write some HTML in index.html:

<!DOCTYPE html>
<html>
<head>
    <title>My First Static Server</title>
</head>
<body>
    <h1>Hello, world!</h1>
</body>
</html>

Here's the Node.js code to serve index.html:

const express = require('express');
const app = express();

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

app.listen(3000, () => {
  console.log('Server is running on port 3000');
});

Now if you access http://localhost:3000/index.html in your browser, you will see the "Hello, world!" heading.

Example 2: Serving multiple types of static files

Now let's add a CSS file and a JavaScript file to the public directory:

  • style.css:
body {
    background-color: lightblue;
}
  • script.js:
document.body.innerHTML += '<p>Hello from JavaScript!</p>';

Update index.html to use these files:

<!DOCTYPE html>
<html>
<head>
    <title>My First Static Server</title>
    <link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
    <h1>Hello, world!</h1>
    <script src="script.js"></script>
</body>
</html>

If you run the server and access http://localhost:3000/index.html, you will see the styled page and the message from the JavaScript file.

4. Summary

In this tutorial, we learned how to serve static files in Node.js using Express.js. We learned how to use the express.static middleware function to serve static files from a directory.

Next, you could learn more about middleware in Express.js, or how to set up routes to handle different requests.

Here's the Express.js documentation for further reading.

5. Practice Exercises

  1. Exercise: Serve static files from a different directory (not public).
    Solution: You just need to change the argument to express.static. For example, if you want to serve files from a directory named static-files, you would use app.use(express.static('static-files')).

  2. Exercise: Serve static files only on a certain route. For example, serve the public directory only on the /static route.
    Solution: You can add a route as the first argument to app.use. For example, to serve the public directory on the /static route, use app.use('/static', express.static('public')).

Remember to practice and experiment on your own for better understanding!

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Robots.txt Generator

Create robots.txt for better SEO management.

Use tool

Image Compressor

Reduce image file sizes while maintaining quality.

Use tool

Random Name Generator

Generate realistic names with customizable options.

Use tool

Random String Generator

Generate random alphanumeric strings for API keys or unique IDs.

Use tool

Text Diff Checker

Compare two pieces of text to find differences.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help