Let us learn Node.js – Part – II
|In this part let us learn to create Node.js web-based Example
A node.js web application contains the following three parts:
1. Import required modules: The “require” directive is used to load a Node.js module. 2. Create server: You have to establish a server which will listen to client’s request similar to Apache HTTP Server. 3. Read request and return response: Server created in the second step will read HTTP request made by client which can be a browser or console and return the response.
How to create node.js web applications ?
Follow these steps:
1. Import required module: The first step is to use require directive to load http module and store returned HTTP instance into http variable
2. Create server: In the second step, you have to use created http instance and call http.createServer() method to create server instance and then bind it to port 8081 or any other ports using listen method associated with server instance. Pass it a function with request and response parameters and write the sample implementation to return “Hello World”.
3. Read request and return response back to the browser or console using request and response object
In the above example,Line 1 imports the required module
Line 3 creates a http server using createServer() function
Content to be printed in the browser screen is handled through response.end() function in line 4 and Console.log() can be used to print any contents in terminal screen.This node js script is invoked when user hits the port 2020 which is mentioned in line 13
let http=require("http"); http.createServer(function (request,response){ response.writeHead(200,{'Content-Type' : 'text/plain'}0; response.end('Hello world\n'); console.log('message printed in browser screen'); }).listen(2020); console.log('Server running at localhost:2020/');
Now, if you make any changes in the “index.js” file, you need to again run the “node index.js” command.
Screenshot of code execution