How to create a server in NodeJS?

By Gulshan Saini
Published in NodeJS
August 16, 2020
1 min read

Creating a server in NodeJs is pretty straight forward. First, you require the http module

The http module can create a server using the method createServer() method. The createServer() method accepts a function(a request listener) that will be called when the user tries to access the server. The function passed into createServer() accepts req and res arguments where req represents the request from the client and res represents the response from the server.

The createServer() method returns a reference to the web server instance, which itself contains the method listen(). To start the server we have to specify the port using listen() method of server

You can optionally, pass a function as the second argument, to listen() method which will be executed when the server starts successfully.

Now save the above code in a file and name it as server.js. Next, open a terminal and navigate to the directory where code for our server is saved.

In the terminal type node server.js. You might be required to add sudo in front as we are using restricted port 80

Once you have started the server

  • on terminal, you will see output “Server started at port”.
  • if you open the browser at address ””, you should see the message from server “Server is up and running!!”

simple http server in nodejs
simple http server in nodejs


Previous Article
How to list the installed node modules and their dependencies?

Gulshan Saini

Fullstack Developer

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.

Related Posts

What is the max HTTP header size in NodeJS server?

August 17, 2020
1 min
© 2020, All Rights Reserved.

Quick Links

Advertise with usContact Us

Social Media