Node.js — The fundamentals

Guide 01 / 4

Node.js glossary

Understand the Node.js concepts and their place in the mini-blog.

Expected outcome :

Explain each concept by tying it to an operation of the project.

Reading
0%

01 · Getting your bearings in the confirmed path

We pick up the “À table !” mini-blog again with more structure and explicit boundaries between server, build tools and browser.

The running project and the targeted skills

Build a local HTTP API with Node.js's native modules: filterable list, recipe by identifier and validated add; display its data in the browser and test the HTTP responses. The reference data remain Soupe de carottes (20 min), Salade de tomates (10 min) and Tarte aux pommes (45 min).

01. Node.js : exposer et tester une API HTTP de recettes, puis la consommer depuis le navigateur.
02. SCSS : organiser la présentation du mini-blog en modules et compiler une feuille CSS.
03. TypeScript : modéliser les recettes et vérifier les réponses de l’API avant de les afficher.
Remember :

Each course has four guides: glossary, essentials, workshop and resources. The complete files are at the end of the workshop.

Prerequisites and environment

Master the JavaScript basics: functions, objects, arrays, conditions, DOM and events. Use Node.js 24.x and npm, an editor and a terminal. This workshop's server has no external npm dependency; no framework is needed to understand the HTTP mechanisms.

mini-blog-node/
├── package.json
├── src/
│   ├── index.js
│   ├── server.js
│   └── recettes.js
├── public/
│   ├── index.html
│   ├── app.js
│   └── style.css
└── test/
    └── api.test.js
Remember :

Work in a mini-blog-node/ project separate from the Technipédia course files. Keep a copy of each working step. The example paths start from the root of this project.

The method and the limits of the workshop

Read the vocabulary, reproduce a small example, build the workshop then check its results. The short sheets illustrate a concept; only the files announced as complete make up the application to reproduce.

Comprendre → reproduire → modifier → observer → expliquer
Remember :

The Node.js branch is a new teaching implementation: it does not reuse the PHP/PDO server of the beginner path. Its initial storage is in memory; SCSS and TypeScript extend this same Node project.

02 · Understanding the Node.js environment

The language stays JavaScript; the APIs and where it runs change.

Runtime and JavaScript engine

A runtime provides an environment for running a language. Node.js lets you run JavaScript outside the browser with network, file and process APIs.

node --version
node src/index.js
Remember :

document and window do not exist on the server side. The public/app.js file, however, runs in the browser.

Process and port

The Node program is a process that can listen on a TCP port. The browser contacts an address made of a protocol, a host and a port.

http://127.0.0.1:3000
# HTTP, machine locale, port 3000
Remember :

Two servers generally cannot listen on the same address and port at the same time.

ES module and import/export

A module exposes functions with export and loads those of another file with import. type: module in package.json chooses this mode for the project's .js files.

export function doubler(n) { return n * 2; }
// Dans un autre fichier :
import { doubler } from "./calcul.js";
Remember :

Include the .js extension in the relative imports of this workshop.

Native module and npm package

A native module ships with Node.js, for example node:http. An npm package is installed separately. npm is also used to run the project's scripts.

import { createServer } from "node:http";
// Aucun npm install nécessaire pour node:http.

package.json and dependency lock file

package.json describes the project, its scripts and its dependencies. package-lock.json pins the versions resolved after an npm install to make reproduction easier.

npm run dev
npm test
Remember :

The dependency-free Node workshop starts without installation. SCSS then TypeScript will add development tools and a lock file.

Event loop and non-blocking processing

Node coordinates callbacks and asynchronous operations. Waiting for an asynchronous file read lets the process handle other events; a long JavaScript computation always blocks that work.

const contenu = await readFile(urlDuFichier);
Remember :

async does not automatically make a heavy computation parallel. Avoid synchronous reads in request handling.

03 · Describing an HTTP API

The browser and the server agree on addresses and data.

Route, method and resource

A route associates an HTTP method and a path with a handler. The collection is /api/recettes; a specific recipe is /api/recettes/1.

GET /api/recettes
GET /api/recettes/1
POST /api/recettes

Request, response and header

The request carries a method, an address, headers and possibly a body. The response provides a status, headers and content.

Content-Type: application/json; charset=utf-8
Location: /api/recettes/4
Remember :

Content-Type describes the format sent; Location here indicates the address of the created resource.

JSON and data contract

JSON carries objects, arrays and simple values. The blog's contract chooses numbers for duration and servings, and arrays of strings for ingredients and steps.

{"donnees":[{"id":1,"titre":"Soupe de carottes","duree_minutes":20,"portions":2,"categorie":"Plat","ingredients":["4 carottes"],"etapes":["Cuire."]}],"total":1}
Remember :

In the PHP/MySQL courses, ingredients and steps were multiline text. A future SQL connection to this API will have to explicitly convert that text into arrays.

Useful HTTP statuses

200 indicates a successful read, 201 a creation. 400 signals a malformed request, 404 an absence, 405 a refused method, 413 a body that is too large, 415 a refused format and 422 inconsistent fields.

JSON mal formé → 400
Durée négative dans un JSON valide → 422
Recette ajoutée → 201

Promise, async and await

A promise represents a future result or a failure. async lets you use await to wait for that result in the function; try/catch handles failures.

async function lireRecettes() {
  const reponse = await fetch("http://127.0.0.1:3000/api/recettes");
  if (!reponse.ok) throw new Error(`HTTP ${reponse.status}`);
  return reponse.json();
}
Remember :

fetch does not automatically reject 404 or 500 responses: check reponse.ok.

Origin and CORS

The origin consists of protocol, host and port. The workshop server serves the page and the API on the same origin: no CORS setting is needed.

Page : http://127.0.0.1:3000/
API : http://127.0.0.1:3000/api/recettes
Remember :

Opening the page from another port or file:// changes this situation; use the URL served by Node.