Friday, 3 November 2017

Node JS | Hello World in Node JS

A Node.js application consists of the following three important components. Components are:

1. Import required modules – the require directive to load Node.js modules.

2. Create server − A server which will listen to client's requests similar to Apache HTTP Server.

3. Read request and return response − Created server will read the HTTP request made by the client who can be a browser or a console and return the response.


<!-- 1. Import required modules -->
var http = require("http");

<!-- 2. Create server -->
http.createServer(function (request, response) {

   // Send the HTTP header
   // HTTP Status: 200 : OK
   // Content Type: text/plain
   response.writeHead(200, {'Content-Type': 'text/plain'});
  
   // Send the response body as "Hello World"
   response.end('Hello World\n');
}).listen(8081);

// Console will print the message
console.log('Server running at http://127.0.0.1:8081/');

Output: Open the browser with http://127.0.0.1:8081/.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...