0
0
Node.jsframework~5 mins

Why building HTTP servers matters in Node.js

Choose your learning style9 modes available
Introduction

Building HTTP servers lets your computer talk to other devices over the internet. It helps deliver websites, apps, and data to users anywhere.

You want to create a website that people can visit from their browsers.
You need to build an app that shares data between users in real time.
You want to make an API so other programs can get or send information.
You want to control smart devices remotely through the internet.
You want to learn how web communication works behind the scenes.
Syntax
Node.js
import http from 'node:http';

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World!');
});

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

This code creates a simple HTTP server that listens on port 3000.

The server sends a plain text response saying 'Hello World!' to anyone who visits.

Examples
A minimal server that responds with 'Hi there!' on port 8080.
Node.js
import http from 'node:http';

const server = http.createServer((req, res) => {
  res.end('Hi there!');
});

server.listen(8080);
Server that shows a welcome message on the home page and a 404 message on other pages.
Node.js
import http from 'node:http';

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h1>Welcome Home</h1>');
  } else {
    res.writeHead(404);
    res.end('Page not found');
  }
});

server.listen(5000);
Sample Program

This program creates a simple HTTP server that listens on port 3000. When you visit http://localhost:3000/ in your browser, it shows the text 'Hello World!'. The console logs a message to confirm the server is running.

Node.js
import http from 'node:http';

const server = http.createServer((req, res) => {
  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('Hello World!');
});

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

HTTP servers are the backbone of the web, delivering content to browsers and apps.

Node.js makes it easy to create servers with just a few lines of code.

Always choose a port number above 1024 to avoid permission issues on your computer.

Summary

HTTP servers let your computer share information over the internet.

Node.js provides simple tools to build these servers quickly.

Understanding servers helps you create websites, apps, and APIs.