Second Introduction To Node.js

Today I’m going to continue to talk about Node.js after my first article (click here to see). Now I’m going to create a web server in Node. The subject of today still is basic and I will pass some concepts about Node that were not learned in the first article. I hope that you have a great read.

For start let’s open the Node prompt (Node.js Command Prompt) according to the following image:

Opening the Node prompt is possible to see the version installed in my computer:

 
 
In the console I started typing the reserved word “Node” and in the next line I typed to print a message, through of function “console.log”. When I key enter, note that the console prints the message.

 

In the image above I continued the code previously, however now I have created a function called “newMessage” and after I called this function passing a parameter that will be showed in the console. The difference between first script and second script it is only the function.

This demonstration is only to show the power of Node console. But this will not be our tool of development.

To start the development I suggest to download the tool “Visual Studio Code”, to ones that still do not have a tool. But you can develop in any tool that you like.

Now, let’s create a basic web server. Follow the code below:

  1. var http = require('http');  
  2.   
  3. var newRequest = function(request, response) {   
  4.     response.writeHead(200, {"Content-Type""text/html"});   
  5.     response.write("<h1>Hello World!</h1>");   
  6.     response.end();   
  7. }   
  8.   
  9. var server = http.createServer(newRequest);  
  10.   
  11. var serverOn = function() {   
  12.     console.log('Server is run!');   
  13. }  
  14.    
  15. server.listen(3000, serverOn);  

For web server works you must go back to Node console and access the folder that you have the code saved and to execute the command “node file_name.js”, where file_name is the name of file that you gave. Our web server will be listening in port 3000 according with the code.

The image below demonstrates the instruction to raise a web server:


 

 

As can be seen, the page show the web server created. Now I’m going to explain the code created.

In the first line I used the http module to create an instance called http. What are modules? Node uses the CommonJs pattern to organize and load the modules. Http is a module that I have loaded. This module Node is responsible by creates a web server. There are many modules and to many things in Node (As files, data base and others). In the next article we’re going to create our own module.

For use the CommonJs pattern is need two rules: The first is that to load a module is needed using the instruction “require”. The second, I’m going to talk in the next article.

In the second instruction was created a function called “newRequest”, in which will be responsible by listen the user request and create a response. For create a response is used the variable response to create the response header and print a text to page.

In the third instruction was created the server through of instance http that calls the function “createServer” where was informed as parameter the function of listener created before.

In the last instruction, the server is raised and will be in the port 3000, the function informed as parameter is only a command that will be executed when the server is raised by the Node.

Now we are going to play with routes within of server that we created. For this, I want to create three routes: home, about and contact, below the code:

  1. var http = require('http');  
  2.   
  3. var newRequest = function(request, response) 
  4. {   
  5.     response.writeHead(200, {"Content-Type""text/html"});  
  6.        
  7.     if(request.url == '/')  
  8.         response.write("<h1>Home</h1>");  
  9.     else if(request.url == '/sobre')  
  10.         response.write("<h1>About</h1>");  
  11.     else if(request.url == '/contato')  
  12.         response.write("<h1>Contact</h1>");  
  13.     else   
  14.         response.write("<h1>Error</h1>");  
  15.           
  16.     response.end();   
  17. }   
  18.   
  19. var server = http.createServer(newRequest);  
  20.   
  21. var serverOn = function() 
  22. {   
  23.     console.log('Servidor Hello World rodando!');   
  24. }     
  25.    
  26. server.listen(3000, serverOn);  

The code above is a update of the code previous and this new code is the creating of routers through of request parameter that validates the URL and prints the page desired.

With this, we created a basic web server in Node. As Node uses JavaScript, note that many times the parameter of a function it is other function. This is not common in platform as C# or Java. But as was explain in the article previous, he utilizes callback function that make with that the process do not be blocked.

You must be imagining if Node can be utilized to large systems that involve many routes and pages, since the code of today got horrible with many “ifs”. Today was a basic example, but in the next article we will utilize a web framework that will facilitate our lives.

Although today we did a basic web server in Node, the example makes clear the ease to  do a web server in JavaScript. As I said above, in the next article I will pass a framework that will make our application more professional. Here I have completed the article and hope that you have understood and learned more about Node.


Similar Articles