E Tech.

See Node.js API - 3

node:http

This is one of the core modules in Node.js. First, I'll cite some official descriptions to draw a mental map.

Overview

In order to support the full spectrum of possible HTTP applications, the Node.js HTTP API is very low-level. It deals with stream handling and message parsing only. It parses a message into headers and body but it does not parse the actual headers or the body.

http.Agent class

An Agent is responsible for managing connection persistence and reuse for HTTP clients.

http.ClientRequest class

This class extends http.OutgoingMessage, which in turn extends Stream. This object is created internally and returned from http.request(). It represents an in-progress request whose header has already been queued. In http.request(), The ClientRequest instance is a writable stream. If one needs to upload a file with a POST request, then write to the ClientRequest object.

import http from 'node:http';
import { Buffer } from 'node:buffer';

const postData = JSON.stringify({
  'msg': 'Hello World!',
});

const options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(postData),
  },
};

const req = http.request(options, (res) => {
  console.log(`STATUS: ${res.statusCode}`);
  console.log(`HEADERS: ${JSON.stringify(res.headers)}`);
  res.setEncoding('utf8');
  res.on('data', (chunk) => {
    console.log(`BODY: ${chunk}`);
  });
  res.on('end', () => {
    console.log('No more data in response.');
  });
});

req.on('error', (e) => {
  console.error(`problem with request: ${e.message}`);
});

// Write data to request body
req.write(postData);
req.end();

http.Server class

This class extends net.Server. Which in turn extends EventEmitter. The http.server is based on Node.js core concepts.

http.ServerResponse class

This object is created internally by an HTTP server, not by the user. It is passed as the second parameter to the 'request' event. This class extends http.OutgoingMessage.

http.IncomingMessage class

This extends stream.Readable. An IncomingMessage object is created by http.Server or http.ClientRequest and passed as the first argument to the 'request' and 'response' event respectively. It may be used to access response status, headers, and data.

http.OutgoingMessage class

This extends Stream. This class serves as the parent class of http.ClientRequest and http.ServerResponse. It is an abstract outgoing message from the perspective of the participants of an HTTP transaction.

Summary of http module

All streams are instances of EventEmitter. In my understanding, most classses represent different roles in HTTP communication, designed in an event-driven style. Node.js also provides http2 and https modules. They follow the same basic structure as http, but differ based on protocol specific features.

Reference : Stream