Loading, please wait...

Node.js First Application

A Node.js application consists of the following components:

  • Import required modules− we use the require directive to load the http module and store the returned HTTP instance into an http variable.
  • Create server− A server which will hear to client's requests similar to Apache HTTP Server. We use the created http occasion and callcreateServer() method to create a server instance then we bind it at port 8081 the usage of the listen approach associated with the server instance. Pass it a feature with parameters request and response
  • Read request and return response− The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response
  1. Create file js
var http = require ("http");

//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://localhost:3000');

 Run the code, $ node app.js

     Output will be

 Explanation of code:

Step 1 - Import Required Module

Load require directive to the http module and store the returned HTTP instance into an http variable as shown:

var http = require("http");

Step 2 - Create Server

Create http instance and call http.createServer() method to create a server instance and then bind it at port 8081 using the listen method. Pass it a function with parameters request and response.