Node js First Web Server Application

Node.js is an open-source, cross-platform runtime environment that allows developers to create all kinds of server-side tools and applications in JavaScript. Node. js has a built-in module called HTTP, which allows Node. js to transfer data over the Hyper Text Transfer Protocol (HTTP). The HTTP module can create an HTTP server that listens to server ports and gives a response back to the client.

Follow these steps to create Node.js web server application-

1. For creating web server in Node.js, first we need an http module. We can load any module using require() method.

Here, we have included the http module using require() method.

var http = require('http');

2. Create Server - The Http server is created by using createServer() method.

The createServer() method takes callback function. This function takes two arguments request and response. This is called on every page request. The request argument contains client request and the response argument is used to return data back to the client. The listen() method is used to bind the server with a port.

var http = require('http');
http.createServer(function(request, response){

3. Now, we will set the content header and send response to the client server.

var http = require('http');
http.createServer(function(request, response){
    response.writeHead(200, {'Content-Type': 'text/plain'});
    response.end("Good Morning");
console.log("Server is running at http://localhost:8080");

4. First save this file as main.js, open cmd and run this file as -

node main.js

After that, open a browser and type https://localhost:8080

run nodejs on web

Read more articles

General Knowledge

Learn Popular Language