NodeJS Server using Core HTTP Module
Let us understand the core http module in NodeJS, which is the basic building block of frameworks like ExpressJS etc.


Learn How to Master Digital Trust

The State of Consumer Digital ID 2024

Top CIAM Platform 2024
Introduction
In this blog, I will show you how to create a NodeJS server using core http module. We will create a simple server that will serve static assets and a simple API to return some JSON data.
In the process, you will also learn about the request and response objects provided by NodeJS, which are used by every other framework built on top of NodeJS like ExpressJS etc.
Prerequisites
- NodeJS installed on your system. Download from Here
- A basic understanding of JavaScript
With that in mind, let's begin.
Step 1: Initialize the project
- Create a folder by any name and initialize a node project in it using
npm init -y- By this time, you will have a
package.jsonfile in your directory.
- By this time, you will have a
- Create a file called
server.jsin your directory.
Step 2: Add some static content
- Create a directory called
publicat the root of your project. - Add a file named
index.htmlwith the following contentindex.html1<!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <title>Demo</title> 7 </head> 8 <body> 9 <h1>Coming from the Root </h1> 10 </body> 11 </html>
Step 3: Add our server code to serve the static assets
Now we will create a node server that will serve our index.html file when a request is sent to /.
server.js
1const http = require('http');
2 const path = require('path');
3 const fs = require('fs');
4 const PORT = 3000;
5 const hostname = 'localhost';
6// createServer is the http method used to create a web server that takes a callback.
7const server = http.createServer(serverHandler);
8// callback function definition
9function serverHandler(req, res) => {
10if(req.method === 'GET' && req.url === '/') {
11let filePath = path.resolve(__dirname, 'public/index.html')
12let fileExists = fs.existsSync(filePath);
13if (!fileExists) {
14res.statusCode = 404;
15res.setHeader('Content-Type', 'text/html');
16res.end( <html> <body> <h3>Page not found</h3> </body> </html>)
17} else {
18res.statusCode = 200;
19res.setHeader('Content-Type', 'text/html');
20fs.createReadStream(filePath).pipe(res);
21}
22}
23}
24server.listen(PORT, hostname, () => {
25console.log(Server running at ${hostname}:${PORT});
26})Let's understand what just happened in the above code snippet:
-
First of all, we just created a server using the
createServermethod provided by nodehttpmodule.createServertakes a callback which will be called when there is an incoming request withreqandresparameters. -
In our callback function
serverHandler, we have used anifblock to check if the incoming request is aGETrequest and the requesturlis/then code inside if statement will be executed. -
Then, we check if the
index.htmlwhich we want to serve exists or not in our public directory usingexistsSync, which synchronously checks for the file at the given path and returns true if the file exists. -
Then if the file does not exist, we return a 404 status with an HTML response with a Content-Type header to let the browser know that it's an HTML type response.
-
If the file exists, we create a readable stream from it using
createReadStreammethod fromfsmodule and pipe it intoresobject which sends it to the browser. -
Finally, we use
server.listento start our server on the PORT 3000.
Now it's time to test our server. Run node server.js at the root of the project, and you will see the server running on PORT 3000.
Open your browser and enter localhost:3000 in the address bar, and you will get the HTML response.
Step 4: Add a basic API to return some JSON data
Now we will expand our callback, which we passed to createServer to handle one more GET request at /notes, which will return an array of notes to the browser.
Update the serverHandler function with the following code snippet in your server.js file
server.js
1...
2 function serverHandler(req, res) {
3 if(req.method === 'GET' && req.url === '/') {
4 let filePath = path.resolve(__dirname, 'public/index.html')
5 let fileExists = fs.existsSync(filePath);
6 if (!fileExists) {
7 res.statusCode = 404;
8 res.setHeader('Content-Type', 'text/html');
9 res.end(`
10 <html>
11 <body>
12 <h3>Page not found</h3>
13 </body>
14 </html>`)
15 } else {
16 res.statusCode = 200;
17 res.setHeader('Content-Type', 'text/html');
18 fs.createReadStream(filePath).pipe(res);
19 }
20 }
21 // Newly added code
22 if (req.method === 'GET' && req.url === "/notes") {
23 const notes = [
24 {
25 id: 1,
26 title: "Demo Note"
27 },
28 {
29 id: 2,
30 title: "Another Note"
31 }
32 ]
33 res.statusCode = 200;
34 res.setHeader('Content-Type', 'application/json');
35 res.end(JSON.stringify(notes));
36 } else {
37 res.setHeader('Content-Type', 'application/json')
38 res.end(JSON.stringify({message: `${req.method} is not supported for ${req.url}`}))
39 }
40
41}
42...- Here, we have added one more
ifstatement to handle the request coming at/notes. - We return a notes array in the JSON format, and we are setting the Content-Type header to be of
application/jsonfor the browser to process it accordingly. - We have also added an else statement to handle all other requests where we simply return a message to the browser that the request is not supported.
With that, we have created a simple node server to serve static content as well a simple API to return JSON data.
Conclusion
We saw how we had to handle each request with its method and the URL. With an increasing number of routes, such things become hard to manage as we will have to add multiple if statements. And that's why frameworks like ExpressJS, HapiJS exist, which makes creating servers in NodeJS very easy. But it's important to know what happens under the hood as there is no magic happening in those frameworks.
The complete code for this blog can be found at Github Repo.
