Writing the first Nodejs Server

Dhruv Rohatgi
2 min readJan 8, 2021

To implement the Node.js Server, we are going to use the HTTP module. To know all about Nodejs modules, visit nodejs.org/api.

Step 1: Import the HTTP module and assign its value to a constant.

Step 2: Declare a const and assign value as 8000. This is the port at which the server will run. The value can vary according to the requirements.

Step 3: Now we will use the http module to create server and store it in a constant. Also while creating server, a function should be passed that can handle the request and response received on the server.

Step 4: Define the function, requestHandler above the createServer method and pass two arguments. In this example, we are using req aka request and res aka response.

The first argument has a method ‘url’ used as req.url which returns the requested URL on the server, on the other hand res has a method ‘end’ used as res.end that is used to serve the content on internet.

Step 5: Finally, we use server.listen method to listen to the server. Two arguments that are passed include port that we have declared above and a function while catching a error. This function will either return an error or print output on the console.

Congratulations! You have now setup your very own nodejs server on your machine.

Now to run the code, open terminal with the folder directory and type the following command:

node index.js

Check out the Full Code below:

Links to our previous post on Nodejs:

Introduction to Nodejs

Hello World with Node.js

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Dhruv Rohatgi
Dhruv Rohatgi

Written by Dhruv Rohatgi

Designer| Developer| Innovator| Founder at HelixSmartLabs Pvt. Ltd.

No responses yet