Creating a Simple Web Server in Node.js

📘 Node.js 👁 48 views 📅 Nov 05, 2025
⏱ Estimated reading time: 2 min

A web server is a program that receives requests from clients (browsers) and sends back responses.
Node.js makes this easy using its built-in http module, without any external libraries.


1. Import the HTTP Module

The http module allows Node.js to handle web requests and responses.

const http = require('http');

2. Create the Server

Use createServer() to define how the server should respond to requests.

const server = http.createServer((request, response) => { response.writeHead(200, { 'Content-Type': 'text/plain' }); response.end('Welcome to my Node.js Server'); });

Here:

  • request contains client information

  • response is used to send data back

  • 200 indicates a successful request


3. Start Listening on a Port

A port is a communication endpoint. The server waits for requests on a specific port.

server.listen(3000, () => { console.log('Server is running at http://localhost:3000'); });

4. Complete Code Example

const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello! This is a simple Node.js web server.'); }); server.listen(3000, () => { console.log('Server started on port 3000'); });

5. Running the Server

  1. Save the file as server.js

  2. Open terminal and run:

  1. http://localhost:3000

6. Why This Server Works Well

  • Uses non-blocking I/O

  • Handles multiple requests efficiently

  • Requires no external packages

  • Lightweight and fast


7. Use Cases

  • Learning Node.js basics

  • Testing APIs

  • Simple backend services


8. Key Takeaway

With just a few lines of code, Node.js can act as a fully functional web server.
This simplicity, combined with high performance, makes Node.js ideal for building scalable network applications.

  • node server.js
  • Open a browser and visit:


  • 🔒 Some advanced sections are available for Registered Members
    Register Now

    Share this Post


    ← Back to Tutorials

    Popular Competitive Exam Quizzes