Node.js — The fundamentals

Guide 02 / 4

Node.js essentials

Syntax, commands and technical choices explained, with short examples to adapt.

Expected outcome :

Choose a statement or a command and predict its effect.

Reading
0%

01 · Preparing and starting the project

Run the commands from mini-blog-node/.

Checking the environment

Check the version and access to the executables. This workshop targets Node 24.x to keep a precise environment.

node --version
npm --version

Defining the npm scripts

Scripts group the project's commands. start launches the server, dev restarts it on changes, test runs the native tests.

npm start
npm run dev
npm test
Remember :

Create the workshop's complete package.json before running these commands.

Stopping and local configuration

Ctrl+C stops the server. PORT is an optional environment variable; its value is a string before conversion and validation.

PORT=3001 npm start
Remember :

The syntax above is Bash. On another shell, set PORT with its own syntax.

Dependencies and npm scripts, as an extension

A development dependency is used to build or check the project. A normal install updates the lock file; npm ci uses an existing lock file without recalculating it.

npm install --save-dev sass@1
npm ci
Remember :

The first example prepares the SCSS course. npm ci requires a consistent package-lock.json.

02 · Reading and writing the HTTP handlers

The excerpts assume the matching imports and variables; the complete files are in the workshop.

createServer and listen

createServer receives a function called for each request. listen opens listening. The workshop separates creating the server from starting it so that it can be tested.

import { createServer } from "node:http";
const serveur = createServer((req, res) => {
  res.writeHead(200, { "Content-Type": "text/plain; charset=utf-8" });
  res.end("À table !");
});
serveur.listen(3000, "127.0.0.1");

URL and search parameters

URL breaks down the path and the parameters. searchParams avoids splitting the address by hand.

const url = new URL(requete.url, "http://localhost");
const q = url.searchParams.get("q") ?? "";
const duree = url.searchParams.get("duree") ?? "0";
Remember :

The fixed base is only used to parse a relative URL. Parameters still have to be validated.

Validating the filters

The workshop accepts a whole duration from 0 to 1440; 0 means all durations. The text is checked before conversion to reject abc, -1 and 2.5.

const valide = /^\d{1,4}$/.test(dureeSaisie) && Number(dureeSaisie) <= 1440;
Remember :

The search normalises case and edge spaces, but does not remove accents.

Reading a JSON body

An HTTP request is a stream of chunks. The server reads them asynchronously, limits what it keeps in memory, then interprets the JSON.

for await (const morceau of requete) {
  // Compter les octets et conserver les morceaux dans la limite choisie.
}
Remember :

The complete file limits the body to 16 KiB. This memory limit and a timeout do not replace a full policy against a large number of requests.

Copying the allowed fields

After validation, build a new object with only the contract's fields. Do not accept the id sent by the client and do not copy all its properties.

const nouvelle = {
  id: prochainId++,
  titre: valeur.titre.trim(),
  duree_minutes: valeur.duree_minutes
};
Remember :

The complete file also checks servings, category and the line arrays.

Serving the public files

readFile reads files asynchronously. A fixed list associates the allowed URLs with the public files; the src/ files and package.json are not served.

const contenu = await readFile(new URL("../public/index.html", import.meta.url));
Remember :

Do not concatenate a path requested by the user directly to the disk path.

03 · Querying and testing

Start with a simple response, then test the edge cases.

curl for a read

curl displays the content received. -i adds the headers and lets you check the status.

curl -i 'http://127.0.0.1:3000/api/recettes?duree=20'
curl -i http://127.0.0.1:3000/api/recettes/9999
Remember :

Expected: 200 and two recipes, then 404.

curl for a creation

Sending a JSON file makes the body readable and avoids shell escaping errors. Create compote.json from the complete example.

curl -i -X POST http://127.0.0.1:3000/api/recettes -H "Content-Type: application/json" --data-binary @compote.json
Remember :

Expected: 201 and a Location header. Additions disappear when the process restarts.

node:test and assert

The test starts an isolated server on an available port, sends real requests and closes the server at the end. The assertions check behaviours that matter to the client.

npm test
Remember :

The api.test.js file tests search, creation, rejection and file access. No manual server needs to be running for it.