how to serve static files with a http server using nodejs

how to serve static files with a http server using nodejs

ยท

5 min read

In this tutorial we will be learning how to serve static files with http using node js. before starting this you should be familiar with node js and preferrably have created a http server . p.s if you haven't check out my other write up on how to create a http server with node js

Now lets get down to code

Before we start check if you have node installed on your machine by running node -v in your terminal, which should display the version of node you have on your computer.

Screenshot (44).png

When you are certain you have node running on your machine create a folder with the name STATICFILESERVER and open a terminal in that directory now in ur STATICFILESERVER create a folder called public which would hold our static files

lets create a simple html page with some css

in the public sub directory create an index.html and an index.css file

in the index.html paste this code

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <main>
  <section class="sample text">
   <p> this is a sample html page</p>

  </section> 
</main> 
</body>
</html>

this page just displays this text (this is a sample html page)

now for our css file paste in the following :

*, html {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

body {
    margin: 2rem;
    color: rgb(255, 255, 255);
    background-color: black;
}

our css file is also simple

it gets rid of default padding and margin. and sets a margin, backgroundcolor and color

now lets write our server code

to setup our server we will be using certain core node modules

1). the http module : which we will be using to set our server up

2). the path module : which we will be using to get our file path

3). the file system module (fs) : which we will be using to read our file for rendering

importing required modules

now in your STATICFILESERVER root directory create a server.js file and input then following to import the http, fs and path modules

const http = require("http");

const fs = require("fs");

const path = require("path");

remember in node js we use require and not import like in es6 to import files/ modules

setting up the server

next we create a constant server whose value is the http.createServer method which takes a fuction which is called every time a request is made to the server and it has two parameters request and response.

const server = http.createServer((request, response) => { 


});

next lets listen to requests made to the server

server.listen(5000, () => {
  console.log("server listening");
});

using the listen method we listen to requests on port 5000

our server.js file should be lke this now

const http = require("http");
const fs = require("fs");
const path = require("path");


const server = http.createServer((request, response) => { 


});

server.listen(5000, () => {
  console.log("server listening");
});

time to configure our server to render our static file from the public folder

first let us get the path of the file using the path.join method which joins the parts of a path , in this case our public sub directory to the url from the request.

const filePath = path.join("public", ${request.url});

next lets render the requested file

first lets create a function to handle errors

const errorHandler = () => {
    response.statusCode = 500;
    response.end(err);
  };
`

our code should now look like this

const http = require("http");
const fs = require("fs");
const path = require("path");


const server = http.createServer((request, response) => { 

const filePath = path.join("public", `${request.url}`);

const errorHandler = () => {
    response.statusCode = 500;
    response.end(err);
  };

});

server.listen(5000, () => {
  console.log("server listening");
});

next we check if the url equals a certain url string and if it does we use the readFile method of the fs (file system) module , which takes as parameters the path of the file to be read , an encoding and a callback function. In the callback function we check for an error first (p.s it is a practice in node js to have error first callback)

if there is none we set the header using the response.setHeader("Content-Type", "the appropriate content type");

p.s you can send any file to the user as long as the find the proper content-type and input it in there

and send the data gotten from the request to the user

response.end(data);

  if (request.url == "/index.html") {
    fs.readFile(filePath, "utf-8", (err, data) => {
      if (err) {
        errorHandler();
      }
      response.setHeader("Content-Type", "text/html");
      response.end(data);
    });
  } else if (req.url == "/index.css") {
    fs.readFile(filePath, "utf-8", (err, data) => {
      if (err) {
        errorHandler();
      }
      response.setHeader("Content-Type", "text/css");
      response.end(data);
    });
  } else if (req.url == "/nabos.jpeg") {
    fs.readFile(filePath, (err, data) => {
      if (err) {
        errorHandler();
      }
      response.setHeader("Content-Type", "image/jpeg");
      response.end(data);
    });
  } else {
    response.end("file not found");
  }

our final code should look something like this

const http = require("http");
const fs = require("fs");
const path = require("path");

const server = http.createServer((req, res) => {
  const filePath = path.join("public", `${req.url}`);

  const errorHandler = () => {
    res.statusCode = 500;
    res.end(err);
  };

  if (req.url == "/index.html") {
    fs.readFile(filePath, "utf-8", (err, data) => {
      if (err) {
        errorHandler();
      }
      res.setHeader("Content-Type", "text/html");
      res.end(data);
    });
  } else if (req.url == "/index.css") {
    fs.readFile(filePath, "utf-8", (err, data) => {
      if (err) {
        errorHandler();
      }
      res.setHeader("Content-Type", "text/css");
      res.end(data);
    });
  }  else {
    res.end("file not found");
  }
});

server.listen(5000, () => {
  console.log("server listening");
});

I hope you enjoyed this tutorial.

happy coding ๐ŸŽŠ๐ŸŽŠ