VOOZH about

URL: https://www.geeksforgeeks.org/node-js/how-to-use-routes-with-serve-static-files-in-node-js/

โ‡ฑ How to use Routes with serve-static Files in Node.js ? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to use Routes with serve-static Files in Node.js ?

Last Updated : 23 Jul, 2025

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
๐Ÿ‘ Screenshot-2024-07-03-094635

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.

Output : The static files specified for different paths will be served accordingly.

๐Ÿ‘ Image
Comment

Explore