Simple Web Server Program in Node.js

Here we write a simple web server program in Node.js that serves static text to the client’s HTTP requests.

var http = require('http');
http.createServer(function(request, response) {
    response.write('Hello World!!!');
console.log('Server started. Hit http://localhost:8080 on your browser.');
  • The createServer method returns a http.Server object
  • We are passing requestListener callback function as a parameter to createServer which automatically added to the ‘request’ event
  • http.Server emits ‘request’ event when it receives a request
  • The request event passes request and response parameters to the callback function
  • We are setting the HTTP Status Code 200, which is Success response using response.writeHead function.
  • Using response.write we are setting the text to be returned
  • To close the connection and return the response we are calling response.end function
  • In the end, we are calling listen function on http.Server object to start the server and listening for requests on port 8080
  • Hit the URL http://localhost:8080 on a browser, it will return “Hello World!!!”.
See also  Callback Function in Node.js