Wednesday, 16 May 2018

003 Node.js Get Started

Node.js Get Started
An application of Node.js are mainly three part 
1)Module 2)Create server 3)Read request and return response.


Module : Module is a collection of function that are required for  application .Node.js has a set of built-in modules which be directly used in the application.The syntax of include a module is require(). Below is example of Module.

var http = require('http');

You can create your own module in Node.js application.

Create Server : Server listen to client's request.The syntax create a server is http.createServer().
This method create a instance of a server and it will bind with a port.You can define the port number during server instance creation.Below is example of server instance creation.

http.createServer(function (request, response) {
  
}).listen(8081);


Read request / return response : The server will read the HTTP request from client and response to either console or browser.

Below is the simple example of an Node.js application.

Example
var http = require("http");

http.createServer(function (request, response)  
{
   console.log('Hello World\n');
}).listen(8081);

To test this application
1)Created a file named "main" and extension ".js" , that is "main.js".
2)Open the file and paste the above code and save the file.
3)Open Node.js command prompt.
4)Move to the directory where "main.js" file is saved.
5)Write command node main.js and press enter
6)Below is the output of Hellow world in the browser.

 
 
If you wand to see the output in browser ,you have to write code that
write on response.We are adding this two lines. 

  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
 
Now , type  http://127.0.0.1:8081/ in your browser url.Here is the result






No comments:

Post a Comment

বাঙালির বেড়ানো সেরা চারটি ঠিকানা

  বাঙালি মানে ঘোড়া পাগল | দু একদিন ছুটি পেলো মানে বাঙালি চলল ঘুরতে | সে সমুদ্রই হোক , পাহাড়ি হোক বা নদী হোক। বাঙালির ...