Friday, February 3, 2017

Nodejs Create Server


We know what nodejs is, and up to now, we are able to run basic node server. If you have not gone through the previous tutorial please check it here.

Cool, let’s go ahead. Now we will create a more sophisticated application. So what we have up to now-

  var http = require('http');
    
    function onRequest(request, response){
        console.log('request '+ request.url);
        response.writeHead(200,{"Context-Type": "text/plain"});
        response.write('Server running');
        response.end()
       
    }
    http.createServer(onRequest).listen(9000);
    console.log('Server Running');

Add and modify few line of code in it-
  var http = require('http');
 function send404(response){
          response.writeHead(404,{"Context-Type": "text/plain"});
          response.write('Error 404');
          response.end();
    }
    function onRequest(request, response){
        console.log('request '+ request.url);
      if(request.method == 'GET' && request.url == '/'){
        response.writeHead(200,{"Context-Type": "text/plain"});
        response.write('Server running');
        response.end();
       }
       else{
         send404(response);
       }
    }
    http.createServer(onRequest).listen(9000);

    console.log('Server Running');

Save the file as server.js and run it (>node server.js). If you can see “Server Running” message, then we are good to go. Open http://localhost:9000 in your browser. You should see “Server Running” in the browser also.
Now change the URL to http://localhost:9000/somethingelse. You will get a message “Error 404”.

Now let me explain what exactly happened. When we request http://localhos:9000, it comes to the server , and as we setup onRequest as a handler function, it starts executing. Now depending on the condition check on request type & properties, it creates a response and sends it back to the browser. For error handling, we used send404 function. Now same way we can create multiple request and error handler.

Example –

    function onRequest(request, response){
      if(request.method == 'GET' && request.url == '/'){
        response.writeHead(200,{"Context-Type": "text/plain"});
        response.write('Server running');
        response.end();
       }
      else if(request.method == 'GET' && request.url == '/somethingelse'){
        response.writeHead(200,{"Context-Type": "text/plain"});
        response.write('Something else from server');
        response.end();
       }
       else{
         send404(response);
       }
    }

Replace your existing onRequest with just above onRequest and again hit http://localhost:9000/somethingelse .  You should see “Something else from server”.

Return physical files
Now instead of sending string response, let’s send files. To do that we need to add below line at the top of the server.js file–

    var fs = require('fs');

Now just update your onRequest function.

function onRequest(request, response){
        if(request.method == 'GET' && request.url == '/'){
            response.writeHead(200,{"Context-Type": "text/html"});
            fs.createReadStream('./index.html').pipe(response);       
        }
        else if(request.method == 'GET' && request.url == '/script.js'){
            response.writeHead(200,{"Context-Type": "text/plain"});
            fs.createReadStream('./script.js').pipe(response);       
        }
        else{
            send404(response);
        }
    }

[Note : Make sure you have index.html and script.js file in the folder]

Lets see what exactly we did. First we imported fs module (node module) for accessing files. Now in onRequest function we used that fs module to read an existing file and send it back as response.

Example -
index.html- 
<html>
<head><script src="./script.js"/></head>
<body>test</body>
</html>
script.js -
(function(){
console.log('test')
})();

In browser and in console you should see "test".


That’s it for now.

No comments: