A Step-by-Step Guide to Creating a Basic HTTP Server in Node.js
"Creating a basic HTTP server in Node.js is a straightforward process. Node.js has a built-in module called http that makes this easy. Here’s a step-by-step guide to help you through:
Step 1: Install Node.js
Before starting, make sure Node.js is installed on your machine. You can download it from Node.js official website. After installing Node.js, you can verify the installation by running:
node -v
Step 2: Create a Project Directory
Create a folder for your project and navigate into it using your terminal:
mkdir my-http-server
cd my-http-server
Step 3: Initialize a Node.js Project
Initialize a new Node.js project inside the directory:
npm init -y
This will create a package.json file which keeps track of your project's metadata and its dependencies.
Step 4: Create the HTTP Server
-
Create an entry point file (e.g.,
server.js) in your project directory:touch server.js -
Write the server code in
server.js:// Import the http module const http = require('http'); // Define the hostname and port const hostname = '127.0.0.1'; const port = 3000; // Create a server and define the request/response logic const server = http.createServer((req, res) => { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Hello, World!\n'); }); // Make the server listen on the specified port and hostname server.listen(port, hostname, () => { console.log(`Server running at http://${hostname}:${port}/`); });
Step 5: Run the Server
Run your server with Node:
node server.js
Step 6: Test Your Server
Open your web browser or a tool like curl or Postman and navigate to http://127.0.0.1:3000/. You should see the message "Hello, World!".
Additional Tips
-
Handle Different Routes: You can extend your server to handle different routes based on the
req.urlproperty.const server = http.createServer((req, res) => { if (req.url === '/') { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('Home Page\n'); } else if (req.url === '/about') { res.statusCode = 200; res.setHeader('Content-Type', 'text/plain'); res.end('About Page\n'); } else { res.statusCode = 404; res.setHeader('Content-Type', 'text/plain'); res.end('Page Not Found\n'); } }); -
Use Environment Variables: For production, you may want to use environment variables for configuration like port and hostname.
const port = process.env.PORT || 3000; const hostname = process.env.HOSTNAME || '127.0.0.1'; -
Graceful Shutdown: Add logic to handle shutdown gracefully.
process.on('SIGTERM', () => { server.close(() => { console.log('Process terminated') }) });
Congratulations! You now have a basic HTTP server running in Node.js. From here, you can expand your server by adding more routes, connecting to a database, or integrating with a front-end."