Open In App

How to use routes with serve-static files in Node.js ?

Last Updated : 04 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

The purpose of this article is to learn how to use routes to serve static files in Node.js, it has an inbuilt HTTP module to transfer data over the HyperText Transfer Protocol (HTTP) which supports various features that were earlier difficult to use. With the help of the functionality provided by this module complete reconstruction of the document from the sub documents(text, layout description, images, videos, scripts, etc.) is done.

Setting Routes for different URL’s:

app.js




const http = require('http');   
const port = 3000;
  
// Creating Basic http Server
const server = http.createServer((req, res) => {    
  const url = req.url;  // requested url
  const method = req.method;  // requested path
  if(url === "/"// setting response for / path 
  {
      res.end("Path /");
  }
  // setting response for /about path
  else if(url === "/about")  
  {
   res.end("Path /about");
  }
  else  
  {
      // setting response for all other paths
      res.end("Path not found");
  }
  console.log("Url entered "+url);
});
server.listen(port, () => {
  console.log(`Server running at http://:${port}/`);
});


Output:

Serving Static Files using HTTP module :

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}/`);
});


index.html




<!DOCTYPE html>
<!DOCTYPE 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>


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>


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



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads