First Node.js application (Hello World)




Before creating actual “Hello world!” Application with Node.js, let’s see how to use different parts in Node.js application. A Node.js application consists of three important parts as shown below –

  • Import required modules – We use ‘require’ Directive to load a Node.js module.
  • Create Server – a server that listen like Apache HTTP server on the customer’s request.
  • Read request and response – server is created in previous step made by Client HTTP – read request that a browser or a console and are may be the answer.

Create Node.js application

Step 1 – import required module

We use Directive require http – module which create an instance of HTTP and assign it to ‘http’ variable, as follows –

var http = require("http");

Step 2: Create Server

In the next step we use http instance and call http.createServer() method which creates the server instance and then we tie them to port 3000 (this means the server will listen on localhost at port 3000).  http.createServer() takes an anonymous function as an argument . This function will take two parameters parameters request and response. on any request from the client the server will  always return “Hello World”.

http.createServer(function (req, res) {
   // 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(3000);

// Console will print the message
console.log("server is running on http://127.0.0.1:3000/")

Above code is enough to create an HTTP server that that will listen on port 3000 on your localhost.

Step 3: Test Query & Answer

Now combine step 1 and 2 together in a file called app.js and restart our HTTP server , as shown below –

var http = require("http");

http.createServer(function (req, res) {
   // Send the HTTP header 
   // HTTP Status: 200 : OK
   // Content Type: text/plain

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

// Console will print the message
console.log("server is running on http://127.0.0.1:3000/")

Now run the app.js to start the server as follows –

$ node app.js

Check the output. of the server

server is running on http://127.0.0.1:3000/

Node.js Certification Training at Simplilearn.com!


Make a request to Node.js server

Node.js response
Node.js response

Node.js Tutorial for Beginners


Partner Sites

VideoToGifs.com

EasyOnlineConverter.com

SqliteTutorials.com





1 Comment

Leave a Reply

Your email address will not be published.


*