Building a Basic Node.js Web Server

Learn how to build a basic web server using Node.js. Understand core concepts like HTTP request processing and explore Node.js’s event-driven architecture. Follow step-by-step instructions to create an efficient web server.



Understanding the Core Concepts

A web server processes incoming network requests over HTTP and delivers the corresponding content. Node.js, with its event-driven, non-blocking architecture, is well-suited for building efficient web servers.

Creating a Node.js Web Server

  1. Import the HTTP Module:
  2. Syntax
    
    const http = require('http');
                
  3. Create a Server Instance:
  4. Syntax
    
    const server = http.createServer((req, res) => {
      // Request and response handling logic
    });
                

    The createServer method creates an HTTP server instance. The callback function passed to createServer is invoked for each incoming request, providing req (request) and res (response) objects.

  5. Handle Incoming Requests:
  6. Syntax
    
    server.on('request', (req, res) => {
      res.writeHead(200, { 'Content-Type': 'text/plain' });
      res.end('Hello, World!\n');
    });
                

    The req object contains information about the incoming request, such as URL, headers, and request body. The res object is used to send the response back to the client. res.writeHead() sets the response status code (200 for success) and content type. res.write() writes data to the response body. res.end() signals the end of the response.

  7. Start the Server:
  8. Syntax
    
    server.listen(3000, 'localhost', () => {
      console.log('Server running at http://localhost:3000/');
    });
                

    The listen method starts the server on the specified port (3000) and hostname ('localhost').

Handling Different Requests

To handle different requests based on their URLs or other criteria, use the following example:

Syntax

server.on('request', (req, res) => {
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('

Home Page

'); } else if (req.url === '/about') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('

About Us

'); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('Not Found'); } });

In this example, different responses are sent based on the URL of the incoming request.

Complete Example: Simple Node.js Web Server

The following code demonstrates a basic Node.js web server:

Syntax

var http = require('http'); // Import Node.js core module

var server = http.createServer(function (req, res) {   // Create web server
    // Handle incoming requests here...
});

server.listen(5000); // Listen for any incoming requests

console.log('Node.js web server at port 5000 is running..');
        

Run this server by executing node server.js in your terminal. The server will be accessible at http://localhost:5000.

Handling HTTP Requests

The http.createServer() method provides request and response parameters. You can use these to get information about the current HTTP request and send responses. Here’s an example:

Syntax

var http = require('http'); // Import Node.js core module

var server = http.createServer(function (req, res) {   // Create web server
    if (req.url === '/') {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.write('

This is home Page.

'); res.end(); } else if (req.url === '/student') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('

This is student Page.

'); res.end(); } else if (req.url === '/admin') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.write('

This is admin Page.

'); res.end(); } else { res.end('Invalid Request!'); } }); server.listen(5000); // Listen for any incoming requests console.log('Node.js web server at port 5000 is running..');

Test the server by navigating to different URLs. Use curl or your browser to see responses.

Sending JSON Responses

To serve JSON responses, use the following example:

Syntax

var http = require('http'); 

var server = http.createServer(function (req, res) {   
    if (req.url === '/data') {
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.write(JSON.stringify({ message: "Hello World" }));
        res.end();
    }
});

server.listen(5000);

console.log('Node.js web server at port 5000 is running..');
        

Key Points

  • Node.js servers are event-driven, handling multiple requests concurrently.
  • The http module provides core functionality for creating servers.
  • The req and res objects are essential for interacting with clients.
  • Proper response headers and content are crucial for successful HTTP communication.

By understanding these fundamentals, you can build more complex web applications using Node.js. Explore advanced topics like routing, templating, and middleware for efficient web development.