Different Servers in Node.js
Last Updated :
06 Apr, 2023
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 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:
Creating Server using ‘http‘ Module:
Import http module: Import http module and store returned HTTP instance into a variable.
Syntax:
const http = require("http");
Creating and Binding Server: Create a server instance using the 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.
The below example illustrates the use of the HTTP module in Node.js.
Example: Filename: index.js
javascript
const http = require("http");
const PORT = process.env.PORT || 2020;
const server = http.createServer(
function (req, res) {
res.write('Hello geeksforgeeks!');
res.end();
}
)
.listen(PORT, error => {
console.log(`Server listening on port ${PORT}`)
});
|
Run the index.js file using the 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.
Creating Server using ‘https‘ Module:
Note: In order to create an HTTPS server, we need SSL key and certificate, and a built-in https Node.js module.
Import https module: Import https module and store returned HTTP instance into a variable.
Syntax:
const https = require("https");
Creating and Binding Server: Create a server instance using the 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 the key and certificate passed.
- onResponseCallback <Callback>: It is a callback function that is called in response of createServer.
- port <Number>: Ports are in the range 1024 to 65535 containing both registered and Dynamic ports.
The below example illustrates the use of the HTTP module in Node.js.
Example: Filename: index.js
javascript
const https = require('https');
const fs = require('fs');
const port = 8000;
const options = {
key: fs.readFileSync('key.pem'),
cert: fs.readFileSync('cert.pem')
};
https.createServer(options, function (req, res) {
res.writeHead(200);
res.end("Hello GeeksforGeeks");
}).listen(port);
|
Run the 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
const https = require('https');
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
}).on('error', (e) => {
console.log(e);
});
|
Run the 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'}
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 the express module and store returned instance into a variable.
Syntax:
const 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
const 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 that helps to communicate with the client and the server.
- IP <Number>: IPs represent the 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
const express = require('express');
const app = express();
const PORT = process.env.PORT || 2020;
const IP = process.env.IP || 2021;
app.get('/', (req, res) => {
res.send('Hello Vikas_g from geeksforgeeks!');
});
app.get('*', (req, res) => {
res.send('OOPS!! The link is broken...');
});
app.listen(PORT, IP, () => {
console.log(`The Server is running at:
http:
});
|
Run the 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.
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:
const 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 is the name of the host.
The below example illustrates the Hapi module in Node.js.
Example: Filename: index.js
javascript
const Hapi = require('@hapi/hapi');
const server = Hapi.server({
port: 2020,
host: 'localhost'
});
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 the 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.
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 the koa module and store returned instance into a variable.
Syntax:
// Importing koa module
const 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 that helps to communicate with the client and the server.
- IP <Number>: IPs represent the 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
const koa = require('koa');
const app = new koa();
const PORT = process.env.PORT || 2020;
const IP = process.env.IP || 2021;
app.use(function* () {
this.body = "Hello GeeksForGeeks!";
});
app.listen(PORT, IP, () => {
console.log("Server started at port", PORT);
});
|
Run the 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.
Similar Reads
Node.js Process exit Event
The process is the global object in Node.js that keeps track of and contains all the information of the particular node.js process that is executing at a particular time on the machine. The process.exit() method is the method that is used to end the Node.js process. Every process action on the machi
2 min read
Global, Process and buffer in Node.js
Global: Global objects in node.js is available in all the modules and are scoped locally to their respective modules. Some of the global objects are: exportsmodulerequire__filename__dirname The above objects and require functions can be accessed everywhere without importing. Process: A process objec
3 min read
What is Buffer in Node.js ?
In Node, Buffer is used to store and manage binary data. Pure JavaScript is great with Unicode-encoded strings, but it does not handle binary data very well. It is not problematic when we perform an operation on data at the browser level but at the time of dealing with TCP stream and performing a re
3 min read
Difference between React.js and Node.js
1. React.js : This is the Javascript library that was developed by Facebook in 2013. This library was developed in order to improve and enhance the UI for the web apps but with time it has evolved a lot. It is open-source and supports different inbuilt functions and modules like form module, routing
2 min read
How to Exit Process in Node.js ?
In this article, we will see how to exit in NodeJS application. There are different types of methods to exit in Nodejs application, here we have discussed the following four methods. Table of Content Using ctrl+C keyUsing process.exit() FunctionUsing process.exitCode variableUsing process.on() Funct
3 min read
How to create different post request using Node.js ?
A POST request is one of the important requests in all HTTP requests. This request is used for storing the data on the WebServer. For Eg File uploading is a common example of a post request. There are many approached to perform an HTTP POST request in Node.js. Various open-source libraries are also
3 min read
Express.js vs KoaJS in Node.js
Node.js: 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 languag
4 min read
Node.js https.request() Function
Https request function in Node is used to make the http request over secure http or https. It provide more control to the request like setting headers, http methods, adding request data and handle the responses. https.request(options, callback)It is a part of https module and allows to send differen
2 min read
Node.js process.umask() Function
The process object is a global that provides information about, and control over, the current Node.js process. As a global, it is always available to Node.js applications without using require(). It can also be explicitly accessed using require() function. process.umask(mask) sets the Node.js proces
1 min read
Node.js Promise Chaining
Promise chaining: Promise chaining is a syntax that allows you to chain together multiple asynchronous tasks in a specific order. This is great for complex code where one asynchronous task needs to be performed after the completion of a different asynchronous task. To demonstrate promise chaining, t
2 min read
Difference Between process.cwd() and __dirname in Node.js
In Node.js, both process.cwd() and __dirname are used to get the directory paths, but they serve different purposes. The key difference is that process.cwd() returns the current working directory from which the Node.js process was started, while __dirname returns the directory name of the current mo
3 min read
Sequential Functionality in Node.js
It is basically executing Asynchronous Tasks in series or synchronously. Java is Asynchronous in nature and so is the Node. Node handles multiple requests at the same time by using Event loop and callback functions. There are 2 methods to perform different asynchronous functions synchronously or seq
4 min read
RESTful Routes in Node.js
Routing: Routing is one of the most significant parts of your website or web application. Routing in Express is basic, adaptable, and robust. Routing is the mechanism by which requests (as specified by a URL and HTTP method) are routed(directed) to the code that handles them. What is RESTful Routing
4 min read
How to Setup View Engine in Node.js ?
View engines are useful for rendering web pages. There are many view engines available in the market like Mustache, Handlebars, EJS, etc but the most popular among them is EJS which simply stands for Embedded JavaScript. It is a simple templating language/engine that lets its user generate HTML with
2 min read
Difference Between LTS and Stable Version Of Node.js.
When working with Node.js, you might come across two key terms: LTS (Long-Term Support) and Stable versions. The main difference between LTS and Stable Version lies in their intended usage and level of support. LTS versions are designed for production environments where stability and security are pr
4 min read
Express.js router.route() Function
The router.route() function returns an instance of a single route that you can then use to handle HTTP verbs with optional middleware. You can also use the router.route() function to avoid duplicate route naming as well as typing errors. Syntax: router.route( path )Parameter: The path parameter hold
2 min read
Express res.json() Function
The res.json() function sends a JSON response. This method sends a response (with the correct content-type) that is the parameter converted to a JSON string using the JSON.stringify() method. Syntax: res.json( [body] )Parameters: The body parameter is the body that is to be sent in the response. Ret
2 min read
Node.js http.server.listen() Method
The http.server.listen() is an inbuilt application programming interface of the class Server within the HTTP module which is used to start the server by accepting new connections. Syntax: const server.listen(options[, callback])Parameters: This method accepts the following two parameters: option: It
2 min read
Node vs Express
Node.js and Express are two essential tools in the JavaScript ecosystem, especially for server-side development. While they are often used together, they serve different purposes. This article will explain what Node.js and Express are, their key differences, and when to use each. Table of Content No
5 min read