Building an HTTP Server in Node.js

Building an HTTP Server in Node.js

1. Setting Up a Node.js Project

Before writing code for the HTTP server, you need to initialize a Node.js project.

Step 1: Create a Project Directory

mkdir myserver
cd myserver

This creates a new directory named myserver and moves into it.

Step 2: Initialize the Project

Run the following command:

npm init -y

This generates a package.json file with default configurations.


2. Creating an HTTP Server

Node.js has a built-in module called http that allows us to create an HTTP server.

Step 3: Create an index.js File

Inside the myserver directory, create a new file:

touch index.js

Step 4: Import the HTTP Module

Open index.js and write the following code:

const http = require("http"); // Importing the HTTP module

3. Creating the Server

To create a server, we use the http.createServer() method.

Step 5: Define the Server

const server = http.createServer((req, res) => {
    console.log("New request received!"); // Log when a request is received

    res.writeHead(200, { "Content-Type": "text/plain" }); // Set response headers
    res.end("Hello from the server!"); // Send response
});

Explanation:

  • req (request): Contains details about the incoming request.

  • res (response): Used to send a response back to the client.

  • res.writeHead(200, { "Content-Type": "text/plain" }): Sends a status code 200 (OK) and specifies the content type as plain text.

  • res.end("Hello from the server!"): Ends the response and sends the text message.


4. Running the Server

Step 6: Define a Port and Start the Server

Add this code at the end of index.js:

const PORT = 3000; // Define a port number

server.listen(PORT, () => {
    console.log(`Server is running on http://localhost:${PORT}`);
});

Step 7: Start the Server

Run the following command in the terminal:

node index.js

If everything is correct, you should see:

Server is running on http://localhost:3000

5. Testing the Server

Open a browser and go to:

http://localhost:3000

You should see:

Hello from the server!

Alternatively, you can use cURL:

curl http://localhost:3000

6. Handling Different Routes

Modify the server to respond based on the request URL:

const server = http.createServer((req, res) => {
    if (req.url === "/") {
        res.writeHead(200, { "Content-Type": "text/plain" });
        res.end("Welcome to the Home Page!");
    } else if (req.url === "/about") {
        res.writeHead(200, { "Content-Type": "text/plain" });
        res.end("This is the About Page.");
    } else {
        res.writeHead(404, { "Content-Type": "text/plain" });
        res.end("404 Not Found");
    }
});

Now, accessing:


7. Using JSON Responses

Instead of plain text, we can return JSON:

const server = http.createServer((req, res) => {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ message: "Hello from the server!", status: "success" }));
});

Opening http://localhost:3000 now returns:

{
    "message": "Hello from the server!",
    "status": "success"
}

8. Stopping the Server

To stop the server, press:

CTRL + C

in the terminal.


Conclusion

You have successfully built a basic HTTP server in Node.js! You can now:

  • Handle multiple routes

  • Return JSON responses

  • Log incoming requests

For a production-ready server, consider using Express.js, which simplifies the process of building APIs.