Creating a Basic HTTP Server in JavaScript Using Node.js: A Step-by-Step Guide

44 views

"Sure! To write a basic HTTP server in JavaScript without using any libraries, you can utilize the built-in http module that comes with Node.js. Below is an example:

  1. Make sure you have Node.js installed. You can download it from https://nodejs.org.

  2. Create a new file, for example, server.js.

  3. Add the following code to server.js:

// Import the http module
const http = require('http');

// Define the port number and hostname
const hostname = '127.0.0.1';
const port = 3000;

// Create the HTTP server
const server = http.createServer((req, res) => {
  // Set the response HTTP header with HTTP status and Content type
  res.statusCode = 200;
  res.setHeader('Content-Type', 'text/plain');
  
  // Send the response body
  res.end('Hello, World!\n');
});

// Make the server listen to requests on the given port and hostname
server.listen(port, hostname, () => {
  console.log(`Server running at http://${hostname}:${port}/`);
});

Here's what the code does:

  1. It imports the http module provided by Node.js.

  2. It defines the hostname (127.0.0.1 which is localhost) and port (3000).

  3. It creates an HTTP server using http.createServer(). This function takes a callback that will be called every time there's an incoming request. The callback function takes two parameters: req (the request) and res (the response).

  4. The server sets the status code to 200 (which means "OK") and the content type to text/plain.

  5. It sends a "Hello, World!" message as the response body.

  6. The server listens on the specified port and hostname, and when the server starts, it logs a message to the console.

  7. To run the server, open your terminal, navigate to the directory where server.js is located, and execute:

node server.js
  1. Open your browser and navigate to http://127.0.0.1:3000/. You should see "Hello, World!" displayed in the browser.

This example demonstrates a very basic HTTP server. In a real-world application, you would handle various routes, methods (like GET, POST), serve different types of content (e.g., JSON, HTML), and implement more complex logic as needed."