HomeTutorsContact

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

const http = require('http')

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.

const http = require('http')

const server = http.createServer((req, res) =>
  res.end('Server is up and running!!')
)

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

const http = require('http')

const server = http.createServer((req, res) =>
  res.end('Server is up and running!!')
)

server.listen(80)

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

const http = require('http')

const server = http.createServer((req, res) =>
  res.end('Server is up and running!!')
)

server.listen(80, () =>
  console.log(`Server started at port http://127.0.0.1:80`)
)

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 http://127.0.0.1:80”.
  • if you open the browser at address ”http://127.0.0.1:80”, you should see the message from server “Server is up and running!!”

simple http server in nodejs
simple http server in nodejs


Tags

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

Related Posts

NodeJS
What is the max HTTP header size in NodeJS server?
August 17, 2020
1 min
Gulshan Saini

Gulshan Saini

Fullstack Developer

Topics

Angular
JavaScript
Typescript
ReactJS

Subscribe to our newsletter!

We'll send you the best of our blog just once a month. We promise.
© 2021, All Rights Reserved.

Quick Links

Contact UsBrowserCSSPythonPuppeteer

Social Media