Create server using NodeJS for web based app

In last tutorial, we have seen how to print 'hello mars' example, now lets create a server in nodejs. Server is required for web applications to run.

So this example will show to create server in your system, this example can also be found in https://nodejs.org/en/about/


// filename : local-server.js
const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  res.end('Hello World\n');
});

server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Now in command prompt run the node local-server.js local-server-nodejs Now open the local host with port which we have mentioned in the program to view the app on browser http://127.0.0.1:3000/ local-server-app

  • Node provide us with the inbuilt http module which we can use to create the server, import the module by using require
  • We can create a server using the createServer() function, createServer() function takes a callback function as arguments. This callback is executed each time a request is received.
  • The two arguments of createServer() function are request and response
  • request : request contains all the information related to client's request such as URL, custom headers, client info, and more
  • response : response is used to return the data back to the client.
  • console.log() prints the given value or text to the terminal
  • response.end() is an inbuilt function which is used to tell the server that the request has been fulfilled.
  • server.listen() is an inbuilt method used to bind to the port an start listening for incoming connections.

About Author

Article is written by Pavan (a) KarthiQ. Well, I am serving notice period in an MNC, Bangalore. I thought to enrich every person knowledge a little, I always have a feeling, when we teach something, we will learn more than what you know. Knowledge is the only thing that doubles when you spend it.

I have also created the reporter for Protractor Jasmine. Use for your projects without any hesitation

Comment / Suggestion Section
Point our Mistakes and Post Your Suggestions