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 …
Section overview
5 resourcesExplores 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
-
Exercise: Serve static files from a different directory (not
public).
Solution: You just need to change the argument toexpress.static. For example, if you want to serve files from a directory namedstatic-files, you would useapp.use(express.static('static-files')). -
Exercise: Serve static files only on a certain route. For example, serve the
publicdirectory only on the/staticroute.
Solution: You can add a route as the first argument toapp.use. For example, to serve thepublicdirectory on the/staticroute, useapp.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.
Related topics
Keep learning with adjacent tracks.
Popular tools
Helpful utilities for quick tasks.
Latest articles
Fresh insights from the CodiWiki team.
AI in Drug Discovery: Accelerating Medical Breakthroughs
In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…
Read articleAI in Retail: Personalized Shopping and Inventory Management
In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …
Read articleAI 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 articleAI 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 articleAI in Legal Compliance: Ensuring Regulatory Adherence
In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…
Read article