Creating Your First Application With Node.js

In the earlier post, I showed you how to install Node.js in your local machine and how to verify whether it's running correctly or not. If you missed that one, you refer it here.

A Node.js program contains mainly 3 blocks.

  1. Import Required Modules
  2. Create Server
  3. Intercept Request and Return Response

Let's create a program and will explain the blocks in detail with examples.

Basically our program will intercept the request and will send the IP address from where the request originated as the response back to the client. For that first we need to import the http module which can be done using the require attribute as follows

var httpMod = require("http");

Here the httpMod variable will store the http instance returned by the require module. This is the first block in the Node.js program where you import all your modules using the required directive.

In the next block, we will create the server which will listen in the specified port for incoming request from the client and returns the response.

httpMod.createServer(function(request,response)
    {
        response.writeHead(200, {'Content-Type': 'text/plain'});
        
        
        
        response.end("Requested From ->" + request.connection.remoteAddress);
    }
).listen(9095);

To create the server, we will invoke the createServer() method on the instance returned by require attribute. After that we will use the listen() method to specify the port where it will listen for incoming requests.

In the final block, we will write logic handing request and sending out the response to the client. In the createServer method, we have a function with request and response parameters and on to that we are writing the status and content.

Here's the program in full

var httpMod = require("http");

        
httpMod.createServer(function(request,response)
    {
        response.writeHead(200, {'Content-Type': 'text/plain'});
        
        
        
        response.end("Requested From ->" + request.connection.remoteAddress);
    }
).listen(9095);

console.log("Up and running !!!!");

So to see our server in action, first we need to start our server using the following command in the CLI. SampleProgram.js is the name given to the above source for persisting in my file system.

node SampleProgram.js


If the server is started succesfully, then we will see the console message in the terminal window as shown below

Let's send a request to our server, type the below url in addressbar of the browser

http://localhost:9095


And the ip address of our machine will be listed in the page


No Comments

Add a Comment