Back to Explore
GuideVibeFix editorialUpdated Nov 25, 2026

JavaScript Leaves the Browser: Node.js Basics in Practice

Five books in stock, 150930 cents in total, 35 copies; stock.json is 372 bytes, Promise.all reads 3 files into A+B+C, and the small service answers 200, 200, 404. Node v24.22.1 stdlib only, measured.

Real photo: a man in a dark room at a laptop, code reflected on his face and shirt

JavaScript in the browser lets you work with a web page: click a button, change some text, send a request. The same language, run somewhere else, can read and write files, start a server, and handle thousands of connections at once. That somewhere else is Node.js. This guide is a hands-on introduction to Node.js: only its built-in modules, no third-party packages, writing a stock program for a fictional bookshop and then turning it into a small service that answers stock queries. The "Morning Light Bookshop" and every number in this guide are invented to make the ideas clear; they are not real records. But every step was really run: the demo script is demo251_g1.mjs, on Node v24.22.1 with V8 13.6.233.17-node.58, and the Chinese and English runs execute the same logic, so the numbers are identical. Each transcript is saved in this directory.

Here is the conclusion up front: 5 books in stock, worth 150930 cents in total, which is 1509.30 yuan, 35 copies altogether; the stock.json written to a temp directory is 372 bytes in English (351 in Chinese — the only difference is the length of the book titles); Promise.all reads 3 files together and joins them into A+B+C; the small service was checked 3 times, /books and /health both returned 200, and the missing /nope returned 404; broken JSON throws SyntaxError, a missing file throws ENOENT, and both errors were caught by try/catch. Keep those numbers in mind — everything that follows is their expansion.

First, the split: JavaScript in the browser vs JavaScript in Node.js

Many people learn JavaScript in the browser, where you have window, document, and alert. Move to Node.js and all of those are gone, replaced by process, fs, and http. The language itself is the same; what changes is what is available around it. The official docs put it plainly: Node.js is an open-source, cross-platform JavaScript runtime that runs Chrome's V8 engine outside the browser; a Node.js app runs in a single process, without creating a new thread for every request, and instead uses a set of asynchronous I/O primitives that keep JavaScript from blocking.

In plain words: Node.js is best at doing something else while it waits. Reading a file waits on the disk, querying a database waits on the network, and a thread that just sits and waits gets nothing done. Node.js parks those operations and comes back when the result is ready, so a single process can serve thousands of concurrent connections without the burden of managing thread concurrency — a significant source of bugs in the traditional approach. That is why it chose async from the start: async is the norm, blocking is the exception.

The demo starts by checking the environment. Running node demo251_g1.mjs --lang en first prints Node v24.22.1, V8 13.6.233.17-node.58, and the operating system linux. Those three numbers look trivial, but they are the premise of everything that follows: different major versions of Node.js differ in module syntax and default behavior, so the version number is the first thing to state when you report a problem or look something up. Then come two easy traps. First, the demo uses ES modules: the file ends in .mjs and the code uses import. There is no require in ES modules — the measured typeof require is undefined. The official Hello World example gives both forms: the CommonJS form with require('node:http'), and the ES module form with import { createServer } from 'node:http'. Whether you save the file as .js or .mjs decides which form you use. Second, import.meta.url is how an ES module finds its own file location; in the demo it ends with demo251_g1.mjs. My judgment: start new projects on ES modules and do not hop back and forth between the two module systems; when you see old code using require, check the file suffix and the type field in package.json first, then copy the matching style.

Writing the stock: turn money into cents before writing the file

The bookshop's stock is 5 books: Three-Body at 5990 cents, 7 copies; Twenty Thousand Leagues at 3950 cents, 12 copies; To Live at 2900 cents, 5 copies; Siddhartha at 4500 cents, 3 copies; West with the Night at 4200 cents, 8 copies. Why cents instead of yuan? Because a decimal like 59.9 cannot be stored exactly in binary floating point: 59.9 times 7 does not come out as a clean 419.3, and the tiny error is invisible at first but adds up until the books no longer balance. Store money as integer cents, and 5990 times 7 is exactly 41930 — not a cent more, not a cent less. Only divide by 100 at the very end, when a human needs to see 1509.30 yuan. This rule applies beyond this demo: whenever you do money math, convert to the smallest integer unit first and let floating point handle only the final display.

The code that writes the file is short:

import { mkdtempSync, writeFileSync } from "node:fs";
import { join } from "node:path";
import { tmpdir } from "node:os";

const dir = mkdtempSync(join(tmpdir(), "bookstock-"));
const stockPath = join(dir, "stock.json");
const jsonText = JSON.stringify(BOOKS, null, 2);
writeFileSync(stockPath, jsonText, "utf8");

Three choices here are worth noting. First, the Sync in writeFileSync means synchronous: it does not return until the file is written. The demo uses it because a demo has only a few steps and synchronous code reads most plainly; in a real service, a synchronous write blocks the whole process, and the reading step in this demo already uses the async approach, covered in section 5. Second, the 2 in JSON.stringify(BOOKS, null, 2) is the indent in spaces, so the file is human-readable; without it, the whole JSON would be squeezed onto one line. Third, the file is not written into the demo directory but into a fresh folder starting with bookstock- inside the system temp directory, so the demo leaves no litter and cannot accidentally overwrite your own files. The resulting stock.json is 372 bytes in English and 351 in Chinese — the two versions differ only in the book titles, and one Chinese character takes 3 bytes in UTF-8 while one English letter takes 1, so the byte difference comes entirely from the titles; the content is identical.

One difference from Python is worth noting: Python's write() returns how many characters were written, while Node.js writeFileSync returns nothing. To know how many bytes went in, measure it yourself: Buffer.byteLength(jsonText, "utf8") gives 372 in English and 351 in Chinese. That number is not the same as "how many characters the string has": one Chinese character is 1 character but 3 bytes, while one English letter is 1 character and 1 byte. When reading a file, specifying "utf8" returns a string; without an encoding you get a Buffer, a run of raw bytes. Text files use strings, binary files use Buffer — the same division of labor as text mode versus binary mode in Python.

My judgment: before writing a file, settle three questions — where does it go, who will read it, and what happens if the write goes wrong. The demo writes to a temp directory because it is throwaway; for anything meant to last, give the file a fixed home, such as a data directory in the project, and think about what happens if the file is deleted, the disk fills up, or two people write at the same time. The demo does not go into those questions, but they are the real second half of "writing a file".

Reading it back and doing the maths: 5 books, 150930 cents

Something written down only counts if it can be read back. The reading code is just as short:

import { readFileSync } from "node:fs";

const loaded = JSON.parse(readFileSync(stockPath, "utf8"));

readFileSync returns a string, and JSON.parse turns it back into an array. The loaded array has 5 books, and each book's unit price times its stock is that line's amount: Three-Body 5990 times 7 is 41930 cents, Twenty Thousand Leagues 3950 times 12 is 47400 cents, To Live 2900 times 5 is 14500 cents, Siddhartha 4500 times 3 is 13500 cents, West with the Night 4200 times 8 is 33600 cents. The five numbers add up to 150930 cents, or 1509.30 yuan; the total copy count is 7 plus 12 plus 5 plus 3 plus 8, which is 35. The bars on the left of the chart are those five numbers, and the tallest is Twenty Thousand Leagues at 47400 cents — not because it is the most expensive, but because it has the most copies, 12.

One detail is worth pausing on: the types of what JSON.parse returns are decided entirely by the file's contents. A number in the file comes back as a number; a string comes back as a string. If someone edited the file and wrote the price as a string, the multiplication would quietly change meaning — a string times a number in JavaScript is still "helpfully" converted to a number, but a string plus a string is concatenation, and the books would stop balancing. In the demo the file is written by the demo itself, so this cannot happen; in the real world, the first thing to do with data from a file or from outside is to verify it — check every field's type and range before doing maths with it. The type guards in the next guide, on TypeScript, exist precisely for this problem.

Joining paths: never hand-write slashes

Paths are one of the easiest things to break across machines. Windows uses backslashes, macOS and Linux use forward slashes, and a data/stock.json that works on your machine may not find the file on another. The Node.js answer is to always build paths with the path module:

import { join, basename, extname } from "node:path";

join("data", "stock.json");   // data/stock.json
basename(stockPath);          // stock.json
extname(stockPath);           // .json

path.join('data', 'stock.json') produces data/stock.json on this Linux machine and the backslash version automatically on Windows — you do not have to care. The demo also measures two values: basename takes the file name stock.json, and extname takes the suffix .json. Both are everyday tools in real projects: sorting files by suffix, renaming uploads, pulling a file name out of a path for a log line. My judgment: any hand-written slash concatenation in code, such as dir + "/" + name, should be replaced with path.join. Fix it now; fixing it later, the day someone runs your code on Windows, costs much more.

Reading 3 files together: Promise.all is not "faster", it is "waiting together"

Step 5 of the demo writes 3 small files containing A, B, and C, then reads them together with the readFile from fs/promises:

import { readFile } from "node:fs/promises";

const texts = await Promise.all(
  ["a.txt", "b.txt", "c.txt"].map((n) => readFile(join(dir, n), "utf8"))
);
// texts is ["A", "B", "C"], joined into A+B+C

Two ideas need separating here. First, fs/promises is the Promise version of fs: readFile returns a Promise that settles when the file is read, while the earlier readFileSync is the synchronous version that does not return until the read is done. Services should prefer the async version, because a synchronous read blocks the whole process — and while the process is blocked, every other request has to wait in line. Second, Promise.all means "wait together": the 3 read operations start at the same time and the code continues only when all of them are done, joining into A+B+C, 3 files in total. It does not make the disk faster; it overlaps 3 waits. If the 3 files are all large and the disk itself is the bottleneck, reading them together is barely faster than reading them one by one.

await written at the top level of the script is an ES module privilege: .mjs files support top-level await, so there is no need to wrap everything in an async function. One more warning: Promise.all has a hard temper — if any one of the operations fails, the whole Promise.all fails, and the results of the others are lost even if they finished. With 3 files and one missing, the outcome is not "A+B+an error" but a thrown error for the whole operation. If your situation is "take whatever could be read", use Promise.allSettled instead: it reports each file's success or failure as it happened. In the demo all 3 files exist, so both forms give the same result — but which one to pick depends on how much failure you can tolerate.

Starting a small service: three routes, two status codes

The first five steps shuffled files around inside one process; this step turns the stock into a service that others can query over the network:

import { createServer } from "node:http";

const server = createServer((req, res) => {
  if (req.url === "/books") {
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ books: loaded.length, totalCents }));
  } else if (req.url === "/health") {
    res.writeHead(200, { "Content-Type": "text/plain" });
    res.end("ok");
  } else {
    res.writeHead(404, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ error: "not found" }));
  }
});
await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));

The Hello World service in the official docs looks exactly like this: createServer builds a server, and when a request arrives the callback receives req and res — one standing for "what was asked", the other for "how you will answer". The demo recognizes only three paths: /books returns the 5 books and the total of 150930 cents, /health returns an ok, and anything else gets a 404 with {"error":"not found"}. It was checked 3 times, with results 200, 200, and 404, and the table on the right of the chart is the verbatim record of those three checks.

Several details deserve expanding. First, the 0 in server.listen(0, "127.0.0.1") asks the operating system to pick any free port, instead of a fixed port like 3000 — so the demo never fails with "port already in use" on any machine. The price is that the port number is different every time, which is why the demo prints only status codes and bodies, never the port; when you try it yourself, take the actual port from server.address().port. Second, 127.0.0.1 is the loopback address: the service only accepts requests from the same machine, and nobody outside can reach it. To let others on the local network connect, change it to 0.0.0.0 — but that exposes the service, so think first. Third, always set Content-Type correctly: application/json for JSON, text/plain for plain text. The caller decides how to parse the response from that header; leave it out and many clients will guess, and a wrong guess breaks everything.

The demo queries the service with fetch, which needs no import in Node.js — since Node.js 18, fetch is a global, and the browser spelling works as it stands. The /books check returns JSON, parsed with rBooks.json(); the /health check returns plain text, read with rHealth.text(). Both methods are async and need await, because the response body does not necessarily arrive all at once. One more detail: fetch only throws when the network itself fails. When the server answers 404, it does not throw at all — in the demo's /nope check, fetch returned a response normally, only with status 404 and the body {"error":"not found"}. So always look at status first, then decide whether to read the body or raise an error. Do not get that order backwards.

The only two status codes in this guide are 200 and 404. 200 means "it worked"; 404 means "what you asked for does not exist". The demo deliberately makes /nope return 404, because "does not exist" is a sentence a service must know how to say: a service that only ever says 200 leaves its callers unable to tell "found it" from "no such thing". My judgment: when writing an interface, settle the status codes before writing the body — one for success, one for not found, one for bad input, one for an internal server error — and only then write the code.

When things go wrong: errors have names and codes

The last step deliberately breaks two things to see how the program catches them. First, broken JSON:

try {
  JSON.parse('{"broken"');
} catch (e) {
  console.log(e.name); // SyntaxError
}

'{"broken"' is missing its second half, so JSON.parse throws SyntaxError, try/catch catches it, and the program does not crash. Second, a missing file:

try {
  readFileSync(join(dir, "missing.json"), "utf8");
} catch (e) {
  console.log(e.code); // ENOENT
}

Reading a file that does not exist gives an error object whose code is ENOENT. That code is far more reliable than the error message: the message can change with language or version, but the code is stable, so code that needs to detect "file does not exist" should check for ENOENT, not compare message text. Most Node.js errors carry a code — EACCES for insufficient permission, EADDRINUSE for an address already in use. Learn the common ones; searching by code is much faster than searching by a whole error sentence.

One more easily missed point: try/catch only catches synchronous code and awaited async code, not errors thrown inside a callback that has already left your hands. In the demo, errors from await fetch(...) can be caught by try/catch because await pulls them back onto the same line of execution; if you write a callback and it throws, try/catch will not catch it. The test is simple: when that line finishes, does the error come straight back to you? If yes, use try/catch; if no, use another mechanism — attach .catch() to the Promise, or attach uncaughtException on the process as the last line of defense.

What you can do after this guide — and where it stops

After this guide, you should be able to do six things: tell JavaScript in Node.js apart from JavaScript in the browser; write files with fs, store structured data with JSON, and know why money should be kept as integer cents; join paths with path instead of hand-writing slashes; read several files together with fs/promises and Promise.all; start a small routed service with node:http and recognize 200 and 404; and catch broken JSON and missing files with try/catch, recognizing error codes such as ENOENT.

Bar chart of each book's line total in cents and a table of the 3 HTTP checks: total 150930 cents, 35 copies; /books 200, /health 200, /nope 404

The boundary of this guide also needs stating. The site's JavaScript series covers JavaScript in the browser — array methods, DOM events, fetch, localStorage, timers, Web Workers — all used inside web pages. This guide covers the Node.js server-side introduction: different tools, different situations, different traps, so do not mix the two styles while reading. The site's Python file I/O guide covers Python's open and its json and csv modules; it solves the same kind of problem as this guide's JSON storage, but the language, modules, and error reporting are all different. The next guide, on TypeScript, continues with the same bookshop: the same 5 books and the same total of 150930 cents, except that every book gets a type, so a wrong field or a wrong argument type is caught before the program runs.

Three things to try yourself, none needing any package: change the small service so it reads a book title from the command line, returning its unit price and stock when found and 404 when not; swap Promise.all for Promise.allSettled, delete one of the files on purpose, and compare the two results; replace the synchronous writeFileSync with the writeFile from fs/promises and feel the difference between sync and async in the shape of the code. Once you feel that you can put a small service together without a framework, look at a framework such as Express — by then you will understand that what a framework saves you is exactly the repetitive code you have just written by hand.

Views 0Comments 0

Comments (0)

ME
0/1000
Loading comments...

Sources

Browse projectsPublish your project

Related articles