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 language. We often use Node.js for building back-end services like APIs like Web App or Mobile App.
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.
The below example illustrates the use of http module in Node.js.
Example 1: Filename: index.js
// Node.js program to create // http server // Using require to access http module const http = require("http"); // Port number const PORT = process.env.PORT || 2020; // Creating server const 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 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: The above syntax imports the “Hapi” 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 two 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 accepts the host names like localhost/127.0.0.1, google.com, geeksforgeeks.org, etc.
The below example illustrates the HapiJS module in Node.js.
Example 2: Filename: index.js
// Node.js program to create server // using hapi module // Importing hapi module const 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://127.0.0.1:2020/ OR http://localhost:2020/ in a web browser to see the output.