Create A Server In Node JS

Create A Server In Node JS

Knowledge Transfer - NODE JS

Introduction

Node.js is a popular runtime environment that allows you to run JavaScript code on the server side. It uses an event-driven, non-blocking I/O model, making it lightweight and efficient for building scalable network applications.

Prerequisite

Before starting the development, make sure you have the following things:

  1. Node JS Installed

  2. A Proper Text Editor like VSCode

You can start the journey by using the following command :

npm init --y

The above step will initialize an empty project for you where you can write and play with your Node JS code.

STEPS

There are basically 4 major steps involved in the process of creating the server.

  1. Import the HTTP module
const http = require('http')
  1. Initialize variables
const PORT = 8080 || 8081  // choose the other one if first is not available
const HOST = 'localhost'

The two variables will act as a placeholder for the values of PORT and HOST in upcoming steps.

  1. Create a listener
const listener = (req,res)=>{
    res.writeHead(200)
    res.end('Hello from Node JS Server')
}
  1. Create a server and join the listener to the created server
const server = http.createServer(listener)
  1. Start the server at a specific PORT and HOST
server.listen(PORT,HOST,()=>{
    console.log(`Server Running On Port : ${PORT} and Host : ${HOST}) 
})

Run and Test

Run the following command to start the app

SYNTAX: node <filename.js>

node node.js

To check if the server is working properly

SYNTAX: curl http://<host>:<port>

curl http://localhost:8080

Output

If all the above-mentioned steps are followed, then the output will be as follows:

Output when the app start

Server Running On Port : 8080 and Host : localhost

Output when using curl

Hello from Node JS Server

Ending Note

You can find more about http module from the official node website

Did you find this article valuable?

Support Sandeep Rana by becoming a sponsor. Any amount is appreciated!