Node.js / Node.js HTTP and Web Servers

Building a Basic HTTP Server with Node.js

This tutorial will guide you through the process of building a basic HTTP server using Node.js. You'll learn the fundamentals of server-side programming, including how to listen a…

Tutorial 1 of 5 5 resources in this section

Section overview

5 resources

Explores building web servers and handling HTTP requests with Node.js.

Building a Basic HTTP Server with Node.js

1. Introduction

In this tutorial, our goal is to build a basic HTTP server using Node.js. We will be learning the basics of server-side programming, including how to listen and respond to HTTP requests.

What you will learn:
- Basic understanding of server-side programming
- How to create a simple HTTP server with Node.js
- How to listen and respond to HTTP requests

Prerequisites:
- Basic understanding of JavaScript
- Node.js and NPM installed on your machine

2. Step-by-Step Guide

Building an HTTP server with Node.js is quite straightforward. Node.js provides a built-in module called HTTP, which allows Node.js to transfer data over the Hypertext Transfer Protocol (HTTP).

Steps:

  1. Create a new Node.js project: Start by initializing a new Node.js project using the command npm init -y in your terminal.
  2. Create a new JavaScript file: Let's call it server.js.
  3. Import HTTP module: At the top of your server.js file, add the line const http = require('http'); to import the HTTP module.
  4. Create server: Now, we will use the http.createServer() method to create an HTTP server.

3. Code Examples

Here's an example of how to create a basic HTTP server that listens on port 3000:

// Importing the HTTP module
const http = require('http');

// Creating the server
const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');
    res.end('Hello World\n');
});

// The server object listens on port 3000
server.listen(3000, '127.0.0.1', () => {
    console.log("Server listening on port 3000");
});

Explanations:
- We are importing the http module provided by Node.js
- The http.createServer() method turns your computer into an HTTP server. It takes a callback function which will be executed each time a client makes a request to your server.
- The callback function takes two arguments: req (the request object) and res (the response object).
- res.statusCode sets the status code to 200, which is HTTP for OK.
- res.setHeader() sets the response header. Here, we are setting the content type to 'text/plain'.
- res.end() ends the response and sends it to the client. Here, we are sending the string 'Hello World\n'.
- Finally, we tell the server to listen on port 3000.

4. Summary

We learned how to create a basic HTTP server using Node.js. We started by initializing a new Node.js project and then created a new JavaScript file. We imported the HTTP module and used the http.createServer() method to create the server.

To continue learning, try adding more features to your server. You could allow it to serve HTML files, add routing, or even build a basic REST API.

Some additional resources include the Node.js docs, Mozilla Developer Network, and various online coding platforms like Codecademy.

5. Practice Exercises

Exercise 1: Modify the server to return a JSON response containing a greeting message.

Exercise 2: Create a server that serves a simple HTML file.

Exercise 3: Add basic routing to your server. For example, requests to '/about' could return a short bio.

Solutions:
1. To return a JSON response, you will need to change the content type to 'application/json' and the response to a JSON string.

res.setHeader('Content-Type', 'application/json');
res.end(JSON.stringify({ message: 'Hello World' }));
  1. To serve an HTML file, you will need to use the fs (filesystem) module in Node.js.
const fs = require('fs');

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/html');
    fs.readFile('index.html', null, function (error, data) {
        if (error) {
            res.writeHead(404);
            res.write('Whoops! File not found!');
        } else {
            res.write(data);
        }
        res.end();
    });
});
  1. To add basic routing, you can use req.url to get the URL of the request.
const server = http.createServer((req, res) => {
    if (req.url === '/about') {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('This is the about page.');
    } else {
        res.writeHead(200, { 'Content-Type': 'text/plain' });
        res.end('Hello World');
    }
});

Remember to practice and experiment on your own for better understanding and mastery of the concepts.

Need Help Implementing This?

We build custom systems, plugins, and scalable infrastructure.

Discuss Your Project

Related topics

Keep learning with adjacent tracks.

View category

HTML

Learn the fundamental building blocks of the web using HTML.

Explore

CSS

Master CSS to style and format web pages effectively.

Explore

JavaScript

Learn JavaScript to add interactivity and dynamic behavior to web pages.

Explore

Python

Explore Python for web development, data analysis, and automation.

Explore

SQL

Learn SQL to manage and query relational databases.

Explore

PHP

Master PHP to build dynamic and secure web applications.

Explore

Popular tools

Helpful utilities for quick tasks.

Browse tools

Keyword Density Checker

Analyze keyword density for SEO optimization.

Use tool

Open Graph Preview Tool

Preview and test Open Graph meta tags for social media.

Use tool

Image Converter

Convert between different image formats.

Use tool

Time Zone Converter

Convert time between different time zones.

Use tool

PDF to Word Converter

Convert PDF files to editable Word documents.

Use tool

Latest articles

Fresh insights from the CodiWiki team.

Visit blog

AI in Drug Discovery: Accelerating Medical Breakthroughs

In the rapidly evolving landscape of healthcare and pharmaceuticals, Artificial Intelligence (AI) in drug dis…

Read article

AI in Retail: Personalized Shopping and Inventory Management

In the rapidly evolving retail landscape, the integration of Artificial Intelligence (AI) is revolutionizing …

Read article

AI in Public Safety: Predictive Policing and Crime Prevention

In the realm of public safety, the integration of Artificial Intelligence (AI) stands as a beacon of innovati…

Read article

AI in Mental Health: Assisting with Therapy and Diagnostics

In the realm of mental health, the integration of Artificial Intelligence (AI) stands as a beacon of hope and…

Read article

AI in Legal Compliance: Ensuring Regulatory Adherence

In an era where technology continually reshapes the boundaries of industries, Artificial Intelligence (AI) in…

Read article

Need help implementing this?

Get senior engineering support to ship it cleanly and on time.

Get Implementation Help