How to create server in node js

Leave a Comment
Hello guy's After working 3 years in node i finally decided to write tutorials on node. When i started node js i also faced so many challenge so i know how to overcome with this challenges. so let's start with first node js tutorial.

Today we will start first thing which i did in node js. Node create its own webserver so we will learn today how to create server in node js as your first application in node js.
Before we start i hope you already install node js on computer. Let's start with hello world in node js application. Node having 3 important things.


  1. Import module: In node js when we have to import any module we have to use require directive to load node module.
  2. Create server: Server which help to listen client request
  3. Read and response request: The server created in an earlier step will read the HTTP request made by the client which can be a browser or a console and return the response.

Let's start with our app.
var http = require("http");

var server = http.createServer(function(req,res){
  res.end("<h1>Hello world</h1>");
});

server.listen(3000);

console.log("Server running on port 3000");

If you copy above code in your text editor and save file as server.js and run command node server.js then you will get this output.


How to create server in node js
Now let's see what happening in our code.

var http = require("http");

we have to use require directive to use http module. http module is inbuilt module in node. so we don't need install http module we can directly use that module in our app.
var server = http.createServer(function(req,res){
  res.end("<h1>Hello world</h1>");
});
server.listen(3000);


As we talked above our second important thing is creating server. http.createServer method use for creating server and listen method is use to bind our app to server port.Above code basically create our http server which is gonna listen on 3000 port.
var server = http.createServer(function(req,res){
  res.end("<h1>Hello world</h1>");
});
server.listen(3000);


Our third step is to get request and process request to send response. In createServer function we pass parameter req,res to handle that request and process response.

when server is created createServer function call its callback function with req,res parameter. req parameter handle request and res parameter send hello world response to browser. Finally you have your first app running in your pc.

If you have any queries or you want any help or you want to request any tutorials you can comment in comment section

Please comment down below if you have any query and please follows us for more awesome tutorials and keep motivating us .

0 comments:

Post a Comment

Powered by Blogger.