Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

node.js
communitycreator

How to create a server in Node

Ayush Trivedi

In this shot, we are going to learn how to create a server in Node. Node has a built-in module/library called http. http provides us with different methods and properties that are used to set up and configure a server in Node.

We will import the http module and use the createServer() and listen() methods to establish a complete server.

The code below is a simple way to create a server:

const http = require('http')
http.createServer().listen(PORT, callback());

Parameters

  • PORT: A port number that our server will listen on.

  • callback(): After createserver() creates a server and our function listens on the specified port, the callback will be executed.

Code

We will now try to create a server with the http method createServer(). Our main focus will be on establishing a server, not on the routing or creating a response from the server.

Normally, createServer() has a callback function as a parameter, which executes when a client(browser) sends a request or connects to the server. In return, the callback generates a response to that particular request.

const http = require('http')

const port = process.env.PORT || 3000

const server = http.createServer();

server.listen(port, () => {
  console.log(`Server running at port ${port}`)
})

setTimeout(()=>{
  server.close()
},2000)

Explanation

  • In line 1, we import the http module.

  • In line 3, we define a port that the server will listen on.

  • In line 5, we create an instance of http.server with http.createServer(). We do not pass any parameters because we are focusing on creating a server and not on requests and responses by the server.

  • In line 7, we must define server.listen() because, without it, we won’t be able to access our server. After the server is ready, it will start listening to port, which is passed as the first parameter in server.listen(). We also define a function that will be executed when the server starts listening and is ready.

  • In line 14, we use server.close() in setTimeout() of 2 seconds, which will stop the server after 2 seconds.

RELATED TAGS

node.js
communitycreator
RELATED COURSES

View all Courses

Keep Exploring