V8node:fsfiletextlinesDisknotes.txt1eggs2milk3bread1import { readFile } from "node:fs/promises";2const file = process.argv[2];3const text = await readFile(file, "utf8");4const lines = text.trim().split("\n").length;5console.log(`${file}: ${lines} lines`);Terminal$ node count.mjs notes.txtnotes.txt: 3 lines$30
Back: Node.js (the V8 engine, the node:fs built-in, memory) and the diskFront: the program count.mjs and the terminalTokens: the script, instructions, readFile, the file name, the request, the text, 3, the output and the exit codeAt the back, Node.js: the V8 engine, the built-in module node:fs and three memory boxes, and the disk holding notes.txt. In front, the program count.mjs and the terminal. The command starts Node, which runs count.mjs line by line: it imports readFile, takes the file name from process.argv, and asks the disk for the file without blocking V8. When the text arrives it counts three lines, prints notes.txt: 3 lines to the terminal, and exits with code 0. ECMAScript (ECMA-262) defines the language; a host adds the objects around it. A browser adds document and window; Node.js adds process, require (in CommonJS files) and built-in modules such as node:fs. In Node, typeof document is "undefined".

What Node.js is

  1. Node.js runs JavaScript outside the browser. It is the V8 engine, the same one Chrome uses, plus built-in modules for files, networks and processes. There is no web page, so there is no document or window.

Starting a program

Reading a file

Results and exit

What happens

// step 1/9 · node-is
Node.js   = V8 (runs JavaScript)
          + built-in modules (node:fs, node:http, ...)
          + globals such as process
missing   document, window: there is no page
language  the same ECMAScript as in the browser

ECMAScript (ECMA-262) defines the language; a host adds the objects around it. A browser adds document and window; Node.js adds process, require (in CommonJS files) and built-in modules such as node:fs. In Node, typeof document is "undefined". Node.js hands file reads to a small pool of helper threads (its worker pool, from the libuv library). V8 keeps running other JavaScript meanwhile; this program simply has nothing else to do.