How Do I Create a Web Server in Node Js With the HTTP Module?

//

Larry Thompson

Creating a Web Server in Node.js With the HTTP Module

Node.js is a powerful runtime environment that allows you to build scalable and efficient server-side applications. One of its core modules, the HTTP module, enables you to create a web server and handle HTTP requests and responses seamlessly. In this tutorial, we will explore how to create a web server in Node.js using the HTTP module.

Setting Up the Project

Before we dive into creating the web server, let’s make sure we have Node.js installed on our machine. You can download and install Node.js from the official website (https://nodejs.org).

To begin, open your favorite text editor or Integrated Development Environment (IDE) and create a new directory for your project. Navigate to the project directory using your command line interface (CLI) of choice.

Initialize a new Node.js project by running the following command:

$ npm init -y

This command creates a package.json file that keeps track of your project’s dependencies and other metadata.

Creating the Web Server

To create a web server in Node.js, we need to import the core HTTP module. Add the following code snippet to your JavaScript file:

// Importing required modules
const http = require('http');

// Create an instance of HTTP server
const server = http.createServer();

// Start listening on port 3000
server.listen(3000);

This code imports the http module and creates an instance of an HTTP server using createServer(). We then start listening on port 3000 with server.listen(3000). Feel free to change the port number to your preference.

Handling Incoming Requests

To handle incoming requests, we need to define a callback function that will be invoked whenever a request is made to our server. Modify your code as follows:

// Importing required modules
const http = require('http');

// Create an instance of HTTP server
const server = http.createServer((req, res) => {
// Handle incoming requests here
});

The callback function takes two parameters: req (short for request) and res (short for response). These objects represent the incoming request and the outgoing response, respectively. Inside this function, we can process the request and send back a response.

Sending a Response

To send a response, we can use methods available on the res object. Let's modify our code to send a simple "Hello, World!" message as the response:

// Importing required modules
const http = require('http');

// Create an instance of HTTP server
const server = http.createServer((req, res) => {
// Send "Hello, World!" as the response
res.write('Hello, World!');
res.end();
});

In this snippet, we use res.write() to write the "Hello, World!" message to the response stream and res.end() to end the response.

Now when you visit http://localhost:3000 in your browser, you should see the "Hello, World!" message.

Handling Different Routes

In a real-world scenario, we often need to handle different routes and serve different content. Let's modify our code to handle two routes: "/" and "/about".

// Importing required modules
const http = require('http');

// Create an instance of HTTP server
const server = http.createServer((req, res) => {
// Handle different routes
if (req.url === '/') {
res.write('Welcome to the homepage!');
} else if (req.url === '/about') {
res.write('This is the about page.');
} else {
res.write('404 Not Found');
}

res.end();
});

In this example, we use req.url to determine which route was requested. If the route is "/", we send a welcome message.

If it's "/about", we send information about the page. For any other route, we respond with a "404 Not Found" message.

Conclusion

Congratulations! You have successfully created a web server in Node.

We covered how to set up a project, create an HTTP server, handle incoming requests, and send responses. Feel free to experiment further by adding more routes and functionality to your web server!