Different Servers in Node.js - GeeksforGeeks

04 Jan, 2022
Node.js is an open-source and cross-platform runtime environment for executing JavaScript code outside a browser. You need to remember that NodeJS is not a framework and it’s not a programming language. Most of the people are confused and understand it’s a framework or a programming language. We often use Node.js for building back-end services like APIs like Web App or Mobile App.
There are many ways to create a server and even node.js has its own inbuilt server ‘http’. Some of them are mentioned below:
1. Creating Server using ‘http‘ Module:
Import http module: Import http module and store returned HTTP instance into a variable.
Syntax:
var http = require("http");
Creating and Binding Server: Create a server instance using createServer() method and bind it to some port using listen() method.
Syntax:
const server = http.createServer().listen(port)
Parameter: This method (listen()) accepts a single parameter as mentioned above and described below:
port <Number>: Ports are in the range 1024 to 65535 containing both registered and Dynamic ports.
Below example illustrate the use of http module in Node.js.
Example: Filename: index.js
javascript
// Node.js program to create // http server   // Using require to access http module const http = require("http");  // Port numberconst PORT = process.env.PORT || 2020;  // Creating serverconst server = http.createServer(   // Server listening on port 2020   function (req, res) {      res.write('Hello geeksforgeeks!');       // Write a response to the client      res.end();    }).listen(PORT, error => {  // Prints in console  console.log(`Server listening on port ${PORT}`)});
Run index.js file using following command:
node index.js

Output:
Server listening on port 2020
Now type http://127.0.0.1:2020/ OR http://localhost:2020 in a web browser to see the output.
2. Creating Server using ‘https‘ Module:
Note: In order to create an HTTPS server, we need SSL key and certificate, and built-in https Node.js module.
Import https module: Import https module and store returned HTTP instance into a variable.
Syntax:
var https = require("https");
Creating and Binding Server: Create a server instance using createServer() method and bind it to some port using listen() method.
Syntax:
const server = https.createServer(options, 
            onResponseCallback).listen(port)

Parameter: This method accepts three parameters as mentioned above and described below:
options <key, certi>: It includes key and certificate passed.
onResponseCallback <Callback>: It is a callback function which is called in response of createServer.
port <Number>: Ports are in the range 1024 to 65535 containing both registered and Dynamic ports.
Below example illustrate the use of https module in Node.js.
Example: Filename: index.js
javascript
// Node.js program to create // https server   // Using require to access https module var https = require('https');var fs = require('fs');const port= 8000;  var options = {    // Note: We require SSL and certificate  // to create https servers    key: fs.readFileSync('key.pem'),  cert: fs.readFileSync('cert.pem')};  https.createServer(options, function (req, res) {    // Returns the status  res.writeHead(200);  res.end("Hello GeeksforGeeks");}).listen(port);
Run index.js file using the following command:
node index.js
Output:
Hello GeeksforGeeks
Now the server is set up and started, we can get the file by:
curl -k https://localhost:8000
Now type https://127.0.0.1:8000/ OR https://localhost:8000 in a web browser to see the output.
Example: Filename: index.js
javascript
// Node.js program to get the response  // from https server   // Using require to access http module const https = require('https');  // https://www.google.com/https.get('https://www.geeksforgeeks.org/', (res) => {    // Printing status code  console.log('statusCode:', res.statusCode);    // Printing headers  console.log('headers:', res.headers);  }).on('error', (e) => {  console.log(e);});
Run index.js file using the following command:
node index.js

Output:
>> statusCode: 200
>> headers: { server: ‘Apache’, ......... ‘server-timing’: ‘cdn-cache; desc=HIT, edge; dur=1’}
3. Creating Server using ‘Express’ Module: In order to use the express module, we need to install the NPM (Node Package Manager) and the following modules (on cmd).
// Creates package.json file
>> npm init

// Installs express module
>> npm install express --save   OR
>> npm i express -s 

Import express module: Import express module and store returned instance into a variable.
Syntax:
var express = require("express");

Creating Server: The above syntax calls the “express()” function and creates a new express application which gets stored inside the app variable.
Syntax:
const app = express();   
// OR by Importing and creating express application
var express = require("express")(); 

Sending and listening to the response: It communicates the request and response with the client and the server. It requires PORT <number> and IP <number> to communicate. 
app.listen(PORT, IP, Callback);

Parameter: This method accepts three parameters as mentioned above and described below.
PORT <Number>: Ports are the endpoints of communication which helps to communicate with the client and the server.
IP <Number>: IPs represent IPv4 or IPv6 address of a host or a device.
Callback <Function>: It accepts a function.
The below example illustrates the Express.js module in Node.js.
Example: Filename: index.js
javascript
// Node.js program to create server // with help of Express module  // Importing express const express = require('express');  // Creating new express app const app = express();  // PORT configurationconst PORT = process.env.PORT || 2020;  // IP configurationconst IP = process.env.IP || 2021;  // Create a route for the appapp.get('/', (req, res) => {  res.send('Hello Vikas_g from geeksforgeeks!');});  // Create a route for the appapp.get('*', (req, res) => {  res.send('OOPS!! The link is broken...');});  // Server listening to requestsapp.listen(PORT, IP, () => {  console.log(`The Server is running at:           http://localhost:${PORT}/`);});
Run index.js file using the following command:
node index.js

Output:
The Server is running at: http://localhost:2020
Now type http://127.0.0.1:2020/ OR http://localhost:2020/ in a web browser to see the output.
4. Creating Server using ‘Hapi’ Module: In order to use the hapi module, we need to install the NPM (Node Package Manager) and the following modules (on cmd).
// creates package.json file
>> npm init 

// Installs hapi module
>> npm install @hapi/hapi --save 

Import hapi module: Import hapi module and store returned instance into a variable.
Syntax:
var Hapi = require("@hapi/hapi");
Creating Server: The above syntax imports the “express()” module and now it creates a server. It communicates the request and response with the client and the server. It requires PORT <number> and host <string> to communicate.
Syntax:
const server = Hapi.server({port: 2020, host: 'localhost'});

Parameter: This method accepts three parameters as mentioned above and described below.
PORT <Number>: Ports are the endpoints of communication which helps to communicate with the client and the server.
HOST <String>: It it the name of the host.
The below example illustrates the Hapi module in Node.js.
Example: Filename: index.js
javascript
// Node.js program to create server// using hapi module  // Importing hapi moduleconst Hapi = require('@hapi/hapi');      // Creating Server    const server = Hapi.server({        port: 2020,        host: 'localhost'    });      // Creating route    server.route({        method: 'GET',        path: '/',        handler: (request, hnd) => {            return 'Hello GeeksForGeeks!';        }    });  const start = async () => {  await server.start();    console.log('Server running at', server.info.uri);};  process.on('unhandledRejection', (err) => {    console.log(err);    process.exit(1);});  start();
Run index.js file using the following command:
node index.js
Output:
Server running at: http://localhost:2020
Now type http://localhost:2020/ in a web browser to see the output.
5. Creating Server using ‘Koa’ Module: In order to use the Koa module, we need to install the NPM (Node Package Manager) and the following modules (on cmd).
// Creates package.json file
>> npm init 

// Installs express module
>> npm install koa --save  OR
>> npm i koa -s 

Import express module: Import koa module and store returned instance into a variable.
Syntax:
// Importing koa module
var koa = require("koa"); 

Creating Server: The above syntax imports the koa module and creates a new koa application which gets stored inside the app variable.
Syntax:
// Creating koa application
const app = new koa();  

Sending and listening to the response: It communicates the request and response with the client and the server. It requires PORT <number> and IP <number> to communicate.
app.listen(PORT, IP, Callback);
Parameter: This method accepts three parameters as mentioned above and described below.
PORT <Number>: Ports are the endpoints of communication which helps to communicate with the client and the server.
IP <Number>: IPs represent IPv4 or IPv6 address of a host or a device.
Callback <Function>: It accepts a function.
The below example illustrates the Koa module in Node.js.
Example: Filename: index.js
javascript
// Node.js program to create server // with help of Koa module  // Importing koa const koa = require('koa');  // Creating new koa appconst app = new koa();  // PORT configurationconst PORT = process.env.PORT || 2020;  // IP configurationconst IP = process.env.IP || 2021;  app.use(function *(){  this.body = "Hello GeeksForGeeks!";});  // Server listening to requestsapp.listen(PORT, IP, ()=>{    console.log("Server started at port", PORT);});
Run index.js file using the following command:
node index.js

Output:
The Server is running at port 2020
Now type http://127.0.0.1:2020/ OR http://localhost:2020/ in a web browser to see the output.
sagartomar9927
Node.js-Misc
Node.js
Web Technologies
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Express.js express.Router() Function
JWT Authentication with Node.js
Express.js req.params Property
Mongoose Populate() Method
Difference between npm i and npm ci in Node.js
Roadmap to Become a Web Developer in 2022
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Top 10 Projects For Beginners To Practice HTML and CSS Skills
Convert a string to an integer in JavaScript