Skip to content
Home » “Program to Create a Simple HTTP Server using Node.js”

“Program to Create a Simple HTTP Server using Node.js”

This blog post will guide you through the process of creating a simple HTTP server using Node.js. You will learn how to set up the server, handle HTTP requests, and send responses back to the client. By the end of this article, you will have a basic understanding of how to create a server using Node.js.

Code

const http = require('http');  
// Create an instance of the http server 
// to handle HTTP requests
let app = http.createServer((req, res) => {
    // Set a response type of plain text 
//     for the response
...    res.writeHead(200, {'Content-Type': 'text/plain'});
    // Send back a response and end the connection
...    res.end('Hello World!\n');
});
// Start the server on port 3000
app.listen(3000, '127.0.0.1');
console.log('Node server running on port 3000');

Code Explanation

The code snippet provided demonstrates how to create an HTTP server using Node.js. Let’s go through it step by step to understand how it works.

Firstly, we import the ‘http’ module using the require() function. This module provides a set of functions and classes to handle HTTP-related operations.

const http = require('http');

Next, we create an instance of the HTTP server by calling the createServer() method. This method takes a callback function as a parameter, which will be executed whenever a new HTTP request is received.

let app = http.createServer((req, res) => {
  // Callback function code
});

Inside the callback function, we set the response type to plain text using the writeHead() method. In this example, we set the status code to 200 and the content type to ‘text/plain’.

res.writeHead(200, {'Content-Type': 'text/plain'});

We then send back a response using the end() method. In this case, we are sending the string ‘Hello World!\n’.

res.end('Hello World!\n');

Finally, we start the server and listen on port 3000 of the local host using the listen() method. We also log a message to the console to indicate that the server is running.

app.listen(3000, '127.0.0.1');
console.log('Node server running on port 3000');

By running this program, you will have a simple HTTP server up and running on your local machine. You can test it by opening a web browser and navigating to http://localhost:3000. You should see the message “Hello World!” displayed on the page.

Conclusion

In this blog post, we learned how to create a simple HTTP server using Node.js. We explored the code snippet step by step and understood the functionality of each component. Now you can use this knowledge to build more complex servers or explore other features of the Node.js ‘http’ module. Have fun exploring and experimenting with Node.js!

Also checkout the following codes.


Program to Load JSONP Data Using JavaScript
How to Use localStorage in JavaScript