Node JS Tutorial - Creating a Server

In this tutorial, we will learn about creating a server using Node.js. The Node.js framework is primarily used to create server-based applications, and it can easily be used to create web servers that serve content to users.

Node.js provides various modules, such as the "http" and "request" modules, which help process server-related requests in the web server space. We will explore how to create a basic web server application using Node.js.

Creating an HTTP Web Server

Let's create an HTTP web server. To do this, go to the project and open the index.js file. Write the following code:


var http=require('http');
var server = http.createServer(function(req,res){
res.writeHead(200,{
'Content-Type':'text/plain'
});
res.end('Hello World!');
});
server.listen(3000);
console.log("Server is listening on port 3000");

Now, run the code. Go to the command prompt and run the index.js file:


node index.js

The server is now running on localhost port 3000. Let's check it out. Switch to the browser and type "localhost:3000" into the URL bar. You should see the text "Hello World!".

Getting the Requested URL

Now, let's get the requested URL. Add the following code:


var http=require('http');
var server = http.createServer(function(req,res){
res.writeHead(200,{
'Content-Type':'text/plain'
});
res.end('requested url is '+req.end);
});
server.listen(3000);
console.log("Server is listening on port 3000");

Let's check it out. You can see that the requested URL is "/". If I change the URL to "/home", you can see that the URL is now "/home".

In this way, you can create a server in Node.js and handle requests and responses. This is a basic example, but it demonstrates the power and flexibility of Node.js as a server-side technology.