Creating a Basic HTTP Server in JavaScript Using Node.js: A Step-by-Step Guide
"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:
-
Make sure you have Node.js installed. You can download it from https://nodejs.org.
-
Create a new file, for example,
server.js
. -
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:
-
It imports the
http
module provided by Node.js. -
It defines the hostname (
127.0.0.1
which is localhost) and port (3000
). -
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) andres
(the response). -
The server sets the status code to 200 (which means "OK") and the content type to
text/plain
. -
It sends a "Hello, World!" message as the response body.
-
The server listens on the specified port and hostname, and when the server starts, it logs a message to the console.
-
To run the server, open your terminal, navigate to the directory where
server.js
is located, and execute:
node server.js
- 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."