How to use Routes with serve-static Files in Node.js ?
Last Updated :
05 Jul, 2024
Using serve-static
files with routes in a Node.js application involves creating a server with Express, defining routes, and serving static files like HTML, CSS, JavaScript, images, etc. Here’s an article explaining how to use serve-static
with routes in Node.js.
Serving Static Files with Routes in Node.js
When building web applications with Node.js, you often need to serve static files like HTML, CSS, JavaScript, and images. The serve-static
middleware in conjunction with Express is a popular way to achieve this. In this article, we’ll walk through the process of using serve-static
to serve static files alongside custom routes in a Node.js application.
Installation Steps
Step 1: Make a folder structure for the project.
mkdir myapp
Step 2: Navigate to the project directory
cd myapp
Step 3: Initialize the NodeJs project inside the myapp folder.
npm init -y
Approach
To use routes with the server-static files:
- Use
http
to create the server and fs
to handle file operations, defining the server port for connections. - Implement a
readAndServe
function to read files asynchronously and send the content as an HTTP response. - Set up
http.createServer
to check the request URL and call readAndServe
with the appropriate file path for each route. - Use
server.listen
on a specified port to begin listening for incoming requests and log a message confirming the server is running. - Develop
index.html
and about.html
with basic content and navigation links, placing them in the same directory as the server script.
Example: Implementation to use routes with serve-static files in NodeJs.
HTML
<!-- index.html -->
<html>
<head>
<title>index</title>
</head>
<body>
<h2>Welcome To GeeksForGeeks</h2>
<p>This is Index file</p>
<p><a href="/about">
Click to go to About Page
</a>
</p>
</body>
</html>
HTML
<!-- about.html -->
<!DOCTYPE html>
<html>
<head>
<title>About</title>
</head>
<body>
<h2>Welcome To About Page</h2>
<p><a href="/">
Click to go to index
</a>
</p>
</body>
</html>
JavaScript
// app.js
const http = require('http');
// File system module used for accessing files in nodejs
const fs = require("fs");
const port = 3000;
// Helper function
function readAndServe(path, res)
{
fs.readFile(path,function(err, data)
{
console.log(data);
// res.setHeader('Content-Type', 'text/html');
res.end(data);
})
}
const server = http.createServer((req, res) => {
const url = req.url;
const method = req.method;
/* Serving static files on specific Routes */
if(url === "/")
{
readAndServe("./index.html",res)
/* The file named index.html will be sent
as a response when the index url is requested */
}
else if(url === "/about")
{
readAndServe("./about.html",res)
/*The about.html file will be sent as a response when
/about is requested */
}
else
{
res.end("Path not found");
/* All paths other than / and /about will send an error as
a response */
}
});
server.listen(port, () => {
console.log(`Server running at http://:${port}/`);
});
Output : The static files specified for different paths will be served accordingly.
Similar Reads
How to Serve Static Content using Node.js ? Accessing static files are very useful when you want to put your static content accessible to the server for usage. To serve static files such as images, CSS files, and JavaScript files, etc we use the built-in middleware in node.js i.e. express.static. Setting up static middleware: You need to crea
2 min read
How to Separate Routers and Controllers in Node.js ? In a Node.js application, especially when using the Express framework, separating routers and controllers is a common practice to keep the codebase organized, maintainable, and scalable. This separation of concerns ensures that routing logic is kept separate from the business logic, making the appli
4 min read
How To Serve Static Files in ExpressJS? 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.Syntaxapp.use(express.static(path.join(__dirname, 'public')));Serves Static Files: This lin
2 min read
How to Setup View Engine in Node.js ? View engines are useful for rendering web pages. There are many view engines available in the market like Mustache, Handlebars, EJS, etc but the most popular among them is EJS which simply stands for Embedded JavaScript. It is a simple templating language/engine that lets its user generate HTML with
2 min read
How to do Templating using ExpressJS in Node.js ? Template Engine : A template engine basically helps us to use the static template files with minimal code. At runtime, the template engine replaces all the variables with actual values at the client-side. Templating Engine Examples: EJS (Embedded JavaScript Templating) Pug Mustache In this article w
2 min read