Sunday 30 September 2018

node.js: Hello World Web application

In this post, I am going to explain how to develop simple web application using node.js framework.

Step 1: Import required modules. I am using http module to develop ‘Hello World’ application.

/* Import http module */
var http = require("http");

‘require’ directive is used to import the modules.

Step 2: Create the server.
http.createServer(function (request, response) {
        
         response.writeHead(200, {'Content-Type': 'text/plain'});

         response.end('Hello World\nWelcome to node.js programming');
        
}).listen(8080);

As you see above snippet,
a.   Server instance listens on port 8080
b.   I am sending the response code as 200
c.   I am setting response type as text/plain
d.   Sending response message to client

Complete application looks like below.

HelloWorld.js
/* Import http module */
var http = require("http");

/* Create the server, that listens on port 8080 */
http.createServer(function(request, response) {

 response.writeHead(200, {
  'Content-Type' : 'text/plain'
 });

 response.end('Hello World\nWelcome to node.js programming');

}).listen(8080);


Run the application by executing the statement ‘node HelloWorld.js’.

Hit the url ‘http://localhost:8080/’, you can able to see below screen.



Previous                                                 Next                                                 Home

No comments:

Post a Comment