T8 Node.js · Lesson 1
The Node runtime
Node.js runs JavaScript outside the browser: the same language, in a different world, with no page to change but a computer to work on. Run a file with node, print to the screen and to the error stream, read the words and settings a program is given, end with an exit code, and see how Node's one engine takes job after job without ever waiting.
- say what Node.js is, and how it differs from JavaScript in a browser
- run a file, a one-line program and a printed expression with node
- print to standard output and standard error, and send each where you want
- read a program's arguments and environment variables from process
- end a program with an exit code that a shell can test
- predict the order in which Node runs code, promises and timers
The back cover
JavaScript was born to make web pages move. Node.js takes the same language out of the browser and onto the computer itself, where there is no page to change, but files to read, programs to run and a network to talk to.
These pages show what Node is, and how to run a program with it. They show its two output streams, the process object that tells a program where and how it runs, and the exit codes it ends with. They also show the event loop, the reason one engine can wait for many things at once.
Before you start
The story: The engine that never waits
Beyond the Archive's stair, the Engine Hall shakes with work. One great engine turns at its centre, and runners in grey coats carry jobs to it and from it: a boiler to heat, a letter to copy, a door to open at six.
This morning the engine has stopped. A clerk fed it one sum so long that it worked on nothing else for an hour, and every runner in the hall stands waiting with a job in hand.
Foreman Ines Tappet does not shout. "One engine, one job at a time," she says. "Never hand it a job that keeps it from the next one. Learn how it runs, and you will never stop it again."
Until now, every program in this course ran in one of two places: in a browser, beside a page, or in the small shell of the Underway. This step brings the two together. Node.js runs the JavaScript you already know, but in a terminal, on the computer itself, where it can read files, answer requests from other machines and run for days.
It builds on these ideas. Each one has a tiny example, so you can check that you remember it.
| What you already know | A tiny example | Where it comes back |
|---|---|---|
| console.log. | console.log("hi") | Node prints the same way. |
| Arrays and objects. | ["pump", "press"].map(f) | The same language, the same values. |
| Functions. | (j) => j.toUpperCase() | Programs are built from them. |
| Promises and await. | await wait(500) | How Node waits without stopping. |
| setTimeout. | setTimeout(f, 1000) | A job for later, on Node's board. |
| A terminal command. | ls -l | node is a command too. |
| Arguments. | cp a.txt b.txt | Words given to a program. |
| Environment variables. | echo $HOME | Settings a program reads. |
| The two output streams. | 2>/dev/null | Normal output and error output. |
| The exit status. | echo $? | How a program says it failed. |
By the end of this lesson you will be able to:
- say what Node.js is, and how it differs from JavaScript in a browser;
- run a file, a one-line program and a printed expression with node;
- print to standard output and standard error, and send each where you want;
- read a program's arguments and environment variables from process;
- end a program with an exit code that a shell can test;
- predict the order in which Node runs code, promises and timers.
How to follow this lesson
Most blocks show a file, app.js, and the command that runs it. Press Run to run them, or Edit to change the file and run it again. Everything happens in the shop's folder, /home/asha/shop, as in the Underway; nothing here can harm a real computer.
In one line
This lesson is about the Node runtime: running JavaScript in a terminal, its output, its process object, its exit codes, and the event loop that orders its work.
What Node is
At a glance
The same recipe can be cooked in a home kitchen or a hotel kitchen. The steps are the same; the tools around them differ.
Node.js is a JavaScript runtime: it runs JavaScript with V8, the engine inside Chrome, but outside the browser. The language is exactly the same, so variables, functions and promises work as before. What changes is the world around it: there is no window and no document, and in their place there is process, the file system and the network.
Take a guess: Who made Node.js, and what was it first meant for?
JavaScript was made for browsers. A browser reads the page, runs the page's JavaScript, and lets that JavaScript change what you see. Node.js, or Node for short, takes the same language out of the browser. It runs JavaScript on the computer itself, from a terminal, with no page at all.
Node's documentation calls it a JavaScript runtime. A runtime is the program that runs your program, with everything your program needs around it. Inside Node is V8, the engine that runs JavaScript in Google Chrome, so the language works exactly as in the Clock Tower. Around V8, Node adds what a program on a computer needs: files, a terminal, and a network.
Here is a first program. The file is called app.js, and the command under it runs it:
app.js
console.log("Hello from the Engine Hall");
Terminal: node app.js
Hello from the Engine Hall
The command node app.js tells Node to read the file and run it. Node runs every line, prints what console.log is given, and stops when there is nothing left to do. The terminal then waits for your next command.
The same language
Everything from the JavaScript steps works in Node: values, functions, arrays, objects, classes, promises. Node even prints values the way the browser's console does:
app.js
const jobs = ["boiler", "pump", "press"];
console.log(jobs.map((j) => j.toUpperCase()));
console.log({ engine: "main", jobs: jobs.length });
Terminal: node app.js
[ 'BOILER', 'PUMP', 'PRESS' ]
{ engine: 'main', jobs: 3 }
A different world
What changes is the world around the language. A browser gives JavaScript a page to work on: window, the browser's window, and document, the page. Node has no page, so those names do not exist. It has others instead:
app.js
console.log(typeof window, typeof document, typeof globalThis, typeof process);
Terminal: node app.js
undefined undefined object object
The operator typeof, from the JavaScript step, names a value's type; undefined means that the name has no value here. The name globalThis is the global object in every JavaScript world. The name process is Node's own: an object that describes the running program, as later sections show.
| In a browser | In Node | |
|---|---|---|
| runs the language with | the browser's engine (V8 in Chrome) | V8 |
| starts when | a page loads | you type a command such as node app.js |
| has | window, document, the page's elements | process, files, the network |
| is used for | pages that respond to a person | servers, tools and scripts |
Worked example 1
Write a program for the Engine Hall that prints the day's jobs in capitals, and how many there are.
What we have: the jobs boiler, pump and press
What we need: two lines: the jobs in capitals, then a count
The plan: an array; map with toUpperCase; console.log twice; run it with node
app.js
const jobs = ["boiler", "pump", "press"];
console.log(jobs.map((j) => j.toUpperCase()));
console.log("jobs today:", jobs.length);
Terminal: node app.js
[ 'BOILER', 'PUMP', 'PRESS' ]
jobs today: 3
- The array and map are plain JavaScript. console.log with two values prints them with a space between, as in the browser.
It prints the three jobs in capitals, then jobs today: 3.
Check: Count the names: boiler, pump and press are three.
A path that fails: document.write(jobs) to show the jobs. There is no page in Node, so the program stops with ReferenceError: document is not defined.
When you are stuck: a program that worked in the browser fails in Node
Read the error's last part: document is not defined, or window is not defined, means the code uses the page.
Node has no page. Keep the code that works on values, and print with console.log instead.
typeof name tells you whether a name exists in Node without stopping the program.
Your turn
node -e 'console.log(typeof document)'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
undefined
- Node has no page.
- typeof gives undefined for a name with no value.
It prints undefined.
What is V8, and where else does it run?Tap to reveal
- It is the engine inside Node.
The JavaScript engine of Google Chrome.
Name one thing a browser gives JavaScript that Node does not, and one thing Node gives that a browser does not.Tap to reveal
- Think of the page, and of the computer.
The browser has document, the page; Node has process, files and the network.
Did you know?
Made for event-driven servers
Node.js was first released on 27 May 2009, and its original author was Ryan Dahl. In a talk at JSConf in Berlin in June 2018, Dahl said that he created and managed Node through its early development, and that his goal was heavily focused on programming event-driven HTTP servers. When Dahl left in 2012, Node had, by that account, more or less reached those goals.
Why it fits here: It answers this topic's question: Ryan Dahl made Node.js in 2009, aiming at event-driven HTTP servers.
Sources: Wikipedia: Node.js; Ryan Dahl: Design Mistakes in Node (JSConf EU 2018)
Which version to run
Node's version numbers carry advice. Its release page says that up to Node.js 26, odd-numbered releases stopped being supported after six months, while even-numbered ones moved to Active LTS, long-term support, which typically means critical bugs are fixed for 30 months in all. From Node.js 27 the cycle is yearly, and every major version moves to LTS. Production apps should run only LTS releases.
Why it fits here: It adds to this topic's Node: production programs should run a long-term support release, kept fixed for about 30 months.
Source: Node.js: Previous releases
In one line
Node.js is a JavaScript runtime: it runs JavaScript with Chrome's V8 engine outside the browser. The language is the same; there is no window or document, and there is process, files and the network instead.
Running a program
At a glance
A program for Node is a plain text file of JavaScript, usually ending in .js. Running it takes one command.
The command node app.js runs the file app.js. For one line of code there is no need for a file: node -e runs a line, and node -p runs it and prints its value too. If the file does not exist, Node stops with the error Cannot find module, shows the path it looked for, and ends with the exit status 1.
Take a guess: Can Node rerun a program by itself every time you save the file?
The usual way to run JavaScript with Node is to put it in a file and give the file's name to the node command. The file's name ends in .js by custom, and Node finds the file even if you leave the ending off:
app.js
console.log("the engine turns");
Terminal: node app.js
node app
the engine turns
the engine turns
Like every command, node can tell you its version. The lessons of this step were checked with Node 22:
In the shop's folder, /home/asha/shop
node --version
v22.23.1
Programs of one line
For a quick sum or a test, you do not need a file. node -e runs the JavaScript you give it (e for evaluate), and node -p runs it and prints its result (p for print):
In the shop's folder, /home/asha/shop
node -e 'console.log(6 * 7)'
node -p '6 * 7'
node -p '"steam".length'
42
42
5
The single quotes keep the shell from reading the program itself, as in the Underway. With -p there is no need for console.log: Node prints the value that the expression gives.
Node with nothing after it
Typed alone, node opens its REPL (read, evaluate, print, loop): a prompt where each line you type runs at once and shows its value. Type .exit, or press Ctrl+D, to leave. It needs a person at the keyboard, so try it in a real terminal; the page's Run button has no REPL.
When the file is not there
Give node a name that matches no file, and it stops at once with a report:
In the shop's folder, /home/asha/shop
node nosuch.js
echo "[$?]"
node:internal/modules/cjs/loader:1433
throw err;
^
Error: Cannot find module '/home/asha/shop/nosuch.js'
at Function._resolveFilename (node:internal/modules/cjs/loader:1430:15)
at defaultResolveImpl (node:internal/modules/cjs/loader:1040:19)
at resolveForCJSWithHooks (node:internal/modules/cjs/loader:1045:22)
at Function._load (node:internal/modules/cjs/loader:1216:25)
at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:36:49 {
code: 'MODULE_NOT_FOUND',
requireStack: []
}
Node.js v22.23.1
[1]
It looks alarming, but only two lines matter. Error: Cannot find module names the full path that Node looked for, /home/asha/shop/nosuch.js: check the name and the folder. The lines that start with at are Node's own steps, which you can skip. The last line gives Node's version, and the exit status 1 says that the program failed.
| Command | What it does |
|---|---|
node app.js | runs the file app.js (node app finds it too) |
node --version | prints Node's version |
node -e 'code' | runs a line of JavaScript |
node -p 'expression' | runs it and prints its value |
node | opens the REPL, in a real terminal |
Worked example 2
How many seconds are there in a day of the engine's work, from six in the morning to ten at night? Find out with Node, without writing a file.
What we have: the hours from 6 to 22
What we need: the number of seconds
The plan: node -p with the sum: (22 - 6) hours, times 60 minutes, times 60 seconds
In the shop's folder, /home/asha/shop
node -p '(22 - 6) * 60 * 60'
57600
- Sixteen hours of 3600 seconds each. -p printed the value without console.log.
The engine works 57,600 seconds a day.
Check: 16 times 3600 is 57,600.
A path that fails: node -e '(22 - 6) * 60 * 60'. It runs the sum and prints nothing: -e only runs code, and the result is thrown away.
When you are stuck: node says Cannot find module
Read the path in the message: it is the file Node looked for.
ls shows the files in the folder; check the spelling and the ending.
If the file is in another folder, cd there first, or give its path, as in node shop/app.js.
Your turn
node -p '2 ** 10'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
1024
- ** raises to a power.
- -p prints the value.
It prints 1024.
What is the difference between node -e and node -p?Tap to reveal
- Which one prints the value by itself?
-e only runs the code; -p also prints its value.
In Node's report for a missing file, which line tells you what went wrong?Tap to reveal
- Look for the word Error.
Error: Cannot find module, with the path Node looked for.
Did you know?
Restart on every save
Node can watch your files for you. Its manual says the option --watch starts Node in watch mode, where changes in the watched files make the process restart. By default it watches the entry file and every module it requires or imports. Added in Node 18.11.0, watch mode became stable in Node 22.0.0, so node --watch app.js reruns the program each time you save.
Why it fits here: It answers this topic's question: node --watch reruns a program whenever a watched file changes.
Check without running
A program can be checked for mistakes in its writing before it runs at all. The Node manual says the option -c, or --check, does a syntax check of the script without executing it. So node --check app.js reports a missing bracket or a misspelt keyword, with its line, and runs none of the program. It is handy before running a script that deletes or sends something.
Why it fits here: It adds a safety step to this topic's node app.js: node --check finds syntax errors without running anything.
In one line
node app.js runs a file; node -e runs a line, and node -p prints its value too. A missing file gives Cannot find module, with the path Node looked for, and the exit status 1.
Output: two streams
At a glance
A program in a terminal has two outlets, as every command does: one for results and one for errors and warnings.
In Node, console.log writes to standard output, and console.error writes to standard error. The shell can send each one where you want, such as results into a file and errors onto the screen. To print text with no newline of its own, use process.stdout.write instead. All of these are only ways to reach the same two streams, as in every other program.
Take a guess: Does console.log always finish writing before the next line of code runs?
In the Underway, every program had two ways to speak: standard output, for its results, and standard error, for its warnings and errors. Both reach the screen, but they can be sent apart. Node gives you both. console.log writes to standard output, and console.error writes to standard error:
app.js
console.log("to the screen");
console.error("to the error stream");
Terminal: node app.js
echo ---
node app.js 2>/dev/null
echo ---
node app.js > out.txt
cat out.txt
to the screen
to the error stream
---
to the screen
---
to the error stream
to the screen
Run once, both lines reach the screen. With 2>/dev/null, the error line is thrown away. With > out.txt, the normal line goes into the file, and only the error line reaches the screen; cat then shows what the file holds. This is the shell's work, not Node's: Node only chooses which stream each line goes to.
| Method | Stream | For |
|---|---|---|
console.log, console.info | standard output | results |
console.error, console.warn | standard error | warnings and errors |
Keep that split in your programs. A person reading the screen sees both; a program that reads your results, or a file they are saved in, gets only the results, never your warnings mixed in.
Printing without a new line
console.log always ends its line. To print part of a line, Node offers process.stdout.write, which writes exactly the text it is given. console.log also fills in markers, as in the browser: %s takes a string, and %d a number:
app.js
process.stdout.write("boiler ");
process.stdout.write("hot\n");
console.log("%s is at %d degrees", "boiler", 95);
Terminal: node app.js
boiler hot
boiler is at 95 degrees
The two writes made one line, because the first wrote no newline. The \n at the end of the second is the newline, written by hand.
Worked example 3
A gauge program must print the readings as its result, and warn about any pump above 80 degrees, so that the readings can be saved to a file without the warnings.
What we have: the readings boiler 95, pump 85, press 40
What we need: readings on standard output, warnings on standard error
The plan: console.log for each reading; console.error for each warning; then run it with > readings.txt and look at the file
app.js
const readings = { boiler: 95, pump: 85, press: 40 };
for (const [name, degrees] of Object.entries(readings)) {
console.log(name, degrees);
if (name === "pump" && degrees > 80) console.error("warning: the pump is hot");
}
Terminal: node app.js > readings.txt
cat readings.txt
warning: the pump is hot
boiler 95
pump 85
press 40
- The warning reached the screen at once. The file holds only the three readings, which is what any later program needs.
The file has three readings, and the warning went to the screen only.
Check: grep warning readings.txt would find nothing.
A path that fails: console.log for the warning as well. The warning would then sit in readings.txt among the numbers, and a program that adds them up would trip over it.
When you are stuck: an error message ends up in your saved results, or is missing from the screen
Check which method printed it: console.log goes to standard output, console.error to standard error.
In the command, > file catches only standard output; 2> file catches standard error.
Run the command with no redirection at all to see both streams on the screen.
Your turn
node -e 'console.error("hot"); console.log("cool")' 2>/dev/null
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
cool
- 2>/dev/null throws standard error away.
- console.error writes to standard error.
It prints cool only.
Which stream does console.warn write to?Tap to reveal
- It is for warnings.
Standard error, as console.error does.
Why does process.stdout.write("a") followed by process.stdout.write("b") print ab on one line?Tap to reveal
- Does write add a newline?
It writes exactly its text, with no newline of its own.
Did you know?
Sometimes at once, sometimes later
Writing to the screen is not always immediate. The Node manual says the writes behind console.log and console.error may be synchronous or not, depending on what they are connected to and the system. Writes to files are synchronous everywhere. Writes to a terminal are synchronous on POSIX systems such as Linux, but writes to a pipe there are asynchronous. The manual says the reasons are partly historical.
Why it fits here: It answers this topic's question: console.log's write is immediate to a terminal on Linux, but not into a pipe.
A stopwatch in the console
The console can time your code. The Node manual says console.time starts a timer, identified by a label, and console.timeEnd with the same label stops it and prints the elapsed time to standard output, in suitable units. Its example: if 3869 ms have passed, console.timeEnd shows 3.869s. So a slow part of a program can be measured with two lines.
Why it fits here: It adds a tool to this topic's console: console.time and console.timeEnd measure how long a piece of code takes.
Source: Node.js manual: console
In one line
console.log writes results to standard output, and console.error writes warnings to standard error; the shell can send each where you want. process.stdout.write prints text with no newline of its own.
What a program is given: process
At a glance
A running program needs to know things about itself: what it was given, what settings surround it, and where it was started. Node keeps them in one object, process.
The array process.argv holds node's own path, then the file's path, then the arguments typed after it, all as strings. The object process.env holds the environment variables, such as HOME. The method process.cwd() gives the folder where the command was typed, which may differ from the folder that holds the file.
Take a guess: Can Node read a .env file by itself, with no extra package?
A program on a computer starts with orders: the words typed after its name, the settings of the terminal it runs in, and the folder it starts from. Node puts them all in one object, process, which describes the running program.
Arguments: process.argv
The list process.argv holds the command's words. Node puts two of its own first, then the words you typed after the file's name:
app.js
console.log(process.argv);
const [job, count] = process.argv.slice(2);
console.log(job, count, typeof count);
console.log(count + 1, Number(count) + 1);
Terminal: node app.js boiler 3
[ '/usr/bin/node', '/home/asha/shop/app.js', 'boiler', '3' ]
boiler 3 string
31 4
The first element is the path of node itself; the second is the full path of the file. So the words you gave start at index 2, and slice(2), from the JavaScript step, takes exactly those. Every argument is a string, even 3: count + 1 joins two strings into 31. Number(count) turns it into a number first, so the sum is 4.
Settings: process.env
The object process.env holds the environment variables of the Underway's lesson 07: settings that a program finds around it, such as HOME. A name that is not set gives undefined. In bash, a setting written just before the command is given to that command alone:
app.js
console.log(process.env.HOME, process.env.SHIFT);
Terminal: node app.js
SHIFT=night node app.js
echo "[$SHIFT]"
/home/asha undefined
/home/asha night
[]
The second run saw SHIFT, the night shift. The shell itself never kept the variable, as the empty brackets show. Node's documentation adds the other direction: a program may change process.env, but the change stays inside that program.
Where the program runs: process.cwd() and __dirname
process.cwd() gives the folder the command was typed in, the current working directory. __dirname and __filename give the folder and the full name of the file being run. They are the same when you run a file from its own folder, and differ when you do not:
app.js
console.log(process.cwd());
console.log(__dirname);
console.log(__filename);
Terminal: node app.js
cd ..
node shop/app.js
/home/asha/shop
/home/asha/shop
/home/asha/shop/app.js
/home/asha
/home/asha/shop
/home/asha/shop/app.js
From /home/asha, the working directory changed, but the file did not move. A program that reads a file kept next to itself should build the path from __dirname, as the files lesson of this step shows.
| Name | Holds | Example |
|---|---|---|
process.argv | node's path, the file's path, then the arguments, all strings | [ '/usr/bin/node', '/home/asha/shop/app.js', 'boiler' ] |
process.env | the environment variables | process.env.HOME |
process.cwd() | the folder the command was typed in | /home/asha |
__dirname, __filename | the program file's folder and full name | /home/asha/shop |
process.platform, process.version | the system and Node's version | linux, v22.23.1 |
Worked example 4
The engine's greeter must greet the shift named on the command line, or the day shift when no name is given, and say how many workers there are.
What we have: node app.js night 12, or node app.js with nothing after it
What we need: Good night shift, 12 workers; or Good day shift, 0 workers
The plan: slice(2) for the words; a default for each with ??; Number for the count
app.js
const [shift = "day", count = "0"] = process.argv.slice(2);
console.log(`Good ${shift} shift, ${Number(count)} workers`);
Terminal: node app.js night 12
node app.js
Good night shift, 12 workers
Good day shift, 0 workers
- A destructuring default, from the modern JavaScript step, fills in a word that was not given. Number turns the count's string into a number.
It greets the night shift, 12 workers, and with no words the day shift.
Check: node app.js evening 3 would print Good evening shift, 3 workers.
A path that fails: using process.argv[0] for the shift. Index 0 is the path of node itself, /usr/bin/node; the first word you typed is at index 2.
When you are stuck: an argument seems to be missing, or a sum gives the wrong answer
Print process.argv whole to see every element: node and the file come first.
Take your words with process.argv.slice(2).
Every argument is a string. Turn numbers into numbers with Number before any arithmetic.
Your turn
node -p 'typeof process.argv[0]'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
string
- process.argv holds strings only.
It prints string.
A program run as node app.js 7 prints process.argv[2] + 1. What does it print, and why?Tap to reveal
- What type is process.argv[2]?
71: the argument is the string 7, and + joins strings.
A program sets process.env.SHIFT = "night". After it ends, does echo $SHIFT in the shell print night?Tap to reveal
- Where do changes to process.env stay?
No: the change stays inside the program.
Did you know?
.env without a package
Node can now read a .env file by itself. Its manual says the option --env-file loads environment variables from a file relative to the current folder, making them available in process.env. It was added in Node 20.6.0 and is no longer experimental since Node 24.10.0 and 22.21.0. So node --env-file=.env app.js works with no extra package, while the .env file stays out of git.
Why it fits here: It answers this topic's question: node --env-file=.env loads a .env file into process.env with no package.
Everything in process.env is text
process.env keeps only strings. The Node manual says that assigning a property on process.env converts the value to a string, so env.test = null stores the text null, not an empty value. It calls this behaviour deprecated, and warns that future versions may throw an error for values that are not a string, a number or a boolean.
Why it fits here: It sharpens this topic's process.env: every value in it is a string, as Node turns anything stored there into text.
Source: Node.js manual: process
In one line
The object process describes the running program: process.argv holds node's path, the file's path, then the arguments, all strings; process.env holds the environment variables; process.cwd() is where the command was typed.
Ending with an exit code
At a glance
Every program ends with an exit code, a number that tells the shell how it went: 0 for success, anything else for a problem.
A Node program exits with 0 when it runs to its end. To choose another code and still let the work finish, set process.exitCode. The call process.exit(n) ends the program at once, with the code n. An uncaught error prints a report of what went wrong and where, and ends the program with 1. The shell can read that code at once.
Take a guess: Can process.exit() cut off output that has not been printed yet?
Every program in the Underway ended with an exit status, or exit code: 0 for success, any other number for a failure, read with $?. Node programs do the same. A program that runs to its end exits with 0:
app.js
console.log("checking the boiler");
Terminal: node app.js
echo "exit status: $?"
checking the boiler
exit status: 0
Choosing the code
There are two ways to choose another code. process.exit(code) ends the program at once, with that code. Nothing after it runs:
app.js
console.log("checking the boiler");
process.exit(2);
console.log("never printed");
Terminal: node app.js
echo "exit status: $?"
checking the boiler
exit status: 2
Setting process.exitCode chooses the code but lets the program finish its work first:
app.js
process.exitCode = 3;
console.log("the boiler is too hot");
Terminal: node app.js
echo "exit status: $?"
the boiler is too hot
exit status: 3
Node's documentation prefers process.exitCode. process.exit stops even work that is still waiting to happen, such as a timer, or text that is still being written. Here the timer never runs:
app.js
setTimeout(() => console.log("saved"), 100);
process.exit(0);
Terminal: node app.js
echo "[$?]"
[0]
When the program crashes
An error that nothing catches ends the program with the exit code 1, after a report on standard error:
app.js
const degrees = 130;
if (degrees > 120) throw new Error("The boiler is too hot");
console.log("all well");
Terminal: node app.js
echo "[$?]"
/home/asha/shop/app.js:2
if (degrees > 120) throw new Error("The boiler is too hot");
^
Error: The boiler is too hot
at Object.<anonymous> (/home/asha/shop/app.js:2:26)
at Module._compile (node:internal/modules/cjs/loader:1781:14)
at Object..js (node:internal/modules/cjs/loader:1913:10)
at Module.load (node:internal/modules/cjs/loader:1505:32)
at Function._load (node:internal/modules/cjs/loader:1309:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:36:49
Node.js v22.23.1
[1]
The report starts with the place: the file and line 2, the line itself, and a caret, ^, under the throw. Then comes the error, and under it the stack: where the program was when it failed. The line that names app.js, 2:26, is yours (line 2, column 26); the lines that name node:internal are Node's own. Node's version ends the report.
Why the code matters
Other programs read the exit code to decide what to do next. The shell's && runs the next command only after a success, and || only after a failure:
app.js
const ok = process.argv[2] === "cool";
if (!ok) process.exitCode = 1;
Terminal: node app.js cool && echo started || echo refused
node app.js hot && echo started || echo refused
started
refused
Build tools, servers that start other programs, and the tests of a later step all work this way. A program that fails but exits with 0 tells them, wrongly, that all went well.
| How the program ends | Exit code |
|---|---|
| it runs to its end | 0, or process.exitCode if set |
process.exit(n) | n, at once, even with work waiting |
process.exitCode = n, then the end | n, after all the work is done |
| an error that nothing catches | 1, after Node's report |
Worked example 5
The boiler check must fail, with the exit code 1, when the temperature given on the command line is above 120, so that a shell can refuse to start the engine.
What we have: node app.js 130, or node app.js 90
What we need: a message, and the exit code 1 above 120, else 0
The plan: Number(process.argv[2]); above 120, console.error and process.exitCode = 1; else console.log
app.js
const degrees = Number(process.argv[2]);
if (degrees > 120) {
console.error("too hot:", degrees);
process.exitCode = 1;
} else {
console.log("safe:", degrees);
}
Terminal: node app.js 130; echo "[$?]"
node app.js 90; echo "[$?]"
too hot: 130
[1]
safe: 90
[0]
- The warning goes to standard error and the code is set, but the program still ends in the ordinary way, as the documentation recommends.
130 gives too hot and the code 1; 90 gives safe and 0.
Check: node app.js 130 && echo start prints nothing more.
A path that fails: process.exit(1) inside a callback while a file is still being written. The program ends at once, and the end of the file may never be written.
When you are stuck: a shell or a tool treats your failed program as a success
Run it, then echo $? at once: it must not print 0 after a failure.
Set process.exitCode = 1 when something goes wrong, or let the error go uncaught.
A try and catch that only prints the error hides the failure: set the exit code in the catch too.
Your turn
node -e 'process.exitCode = 4'; echo $?
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
4
- The program sets the code and ends.
- $? reads it.
It prints 4.
Why does Node's documentation prefer process.exitCode to process.exit()?Tap to reveal
- What happens to work still waiting?
process.exit ends at once, dropping waiting work; exitCode lets it finish.
What exit code does a program have after an error that nothing caught?Tap to reveal
- Look at the end of the crash report's block.
1.
Did you know?
process.exit can cut output short
process.exit does not wait politely. The Node manual says calling it forces the process to exit as quickly as possible, even if asynchronous work is still pending, including writes to standard output and standard error. It adds that in most situations there is no need to call process.exit at all: the process ends by itself when no work is left, and process.exitCode can set the code.
Why it fits here: It answers this topic's question: process.exit can end the program before pending output is written, so process.exitCode is safer.
Source: Node.js manual: process
Last words must be quick
A program can run code as it exits, but only quick code. The Node manual says listeners on the exit event must only do synchronous work. The process exits straight after calling them, and any work still queued in the event loop is abandoned. A timer started in an exit listener therefore never fires.
Why it fits here: It adds a rule to this topic's ending: code that runs on exit must be synchronous, as nothing queued runs afterwards.
Source: Node.js manual: process
In one line
A Node program exits with 0 when it runs to its end. Set process.exitCode to choose another code and let the work finish; process.exit(n) ends at once. An uncaught error prints a report and exits with 1.
One engine, one job at a time: the event loop
At a glance
Node runs your code on one engine, one piece at a time, yet a server built on it can serve many people at once. The secret is that it never waits idly.
Node runs your code to its end, then the nextTick queue, then the promise callbacks, then the event loop's phases: timers, input and output, and setImmediate. Slow work such as reading a file is handed off, and its callback joins the queue when it is done. Only code that never steps aside, such as a long calculation, blocks everything.
Take a guess: Does Node really do everything on one thread?
Node runs your JavaScript one piece at a time, like the hall's one engine. There is no second engine to take over while the first is busy. Work that must wait, a timer, a file being read, an answer from another machine, is handed off; when it is ready, its next job joins a queue. The part of Node that takes the next job from the queue, again and again, is the event loop.
The first rule follows at once: your code runs to its end before any waiting job starts. A timer of 0 milliseconds still waits for the program's last line:
app.js
setTimeout(() => console.log("timer"), 0);
let total = 0;
for (let i = 0; i < 1e6; i++) total += i;
console.log("loop done", total);
Terminal: node app.js
loop done 499999500000
timer
The loop added a million numbers first, and only then did the timer's function run. A function that is handed over to be called later, as the timer's is, is a callback.
The order of the queues
Waiting jobs are not all equal. After your code, Node first runs the functions given to process.nextTick, then the promises' callbacks, then goes round the loop, where timers come first:
app.js
console.log("1: the first line");
setTimeout(() => console.log("4: the timer"), 1000);
Promise.resolve().then(() => console.log("3: the promise"));
process.nextTick(() => console.log("2: nextTick"));
console.log("1: the last line");
Terminal: node app.js
1: the first line
1: the last line
2: nextTick
3: the promise
4: the timer
| Step | What runs |
|---|---|
| 1 | your code, from the first line to the last |
| 2 | the process.nextTick queue |
| 3 | the promise callbacks (then, await) |
| 4 | the event loop's phases, in turn: timers, then I/O callbacks (poll), then setImmediate (check), then close callbacks |
| after each callback, steps 2 and 3 again, before the next one |
The documentation of setImmediate says that it runs its callback in the check phase, just after the I/O callbacks. Inside an I/O callback, an immediate always comes before a timer, even a timer of 0 milliseconds:
app.js
const fs = require("fs");
fs.readFile(__filename, () => {
setTimeout(() => console.log("timeout"), 0);
setImmediate(() => console.log("immediate"));
process.nextTick(() => console.log("nextTick"));
});
Terminal: node app.js
nextTick
immediate
timeout
A race you must not rely on
Called from the main program, outside any I/O callback, the order of setTimeout(f, 0) and setImmediate(g) is not fixed: Node's documentation says it depends on how fast the computer is at that moment. Never write a program whose result depends on it.
Waiting without stopping
A promise that a timer resolves lets a function wait in the middle, with await, while the engine takes other jobs:
app.js
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function shift() {
console.log("boiler on");
await wait(2000);
console.log("boiler hot");
}
shift();
console.log("the engine takes the next job");
Terminal: node app.js
boiler on
the engine takes the next job
boiler hot
shift started, reached await and stepped aside. The last line of the program ran at once; two seconds later the timer resolved the promise, and shift went on from where it had waited. This is how one engine serves a whole hall: it never stands still waiting, it moves to the next job. The one thing that stops it is code that never steps aside, such as a loop of a billion turns.
Worked example 6
Predict the order of this program's lines before running it: a log, a nextTick, a promise, a timer of 0 ms and a final log.
What we have: the program below
What we need: the order of the five lines
The plan: your code first; then nextTick; then promises; then the timer, in the loop
app.js
setTimeout(() => console.log("E"), 0);
Promise.resolve().then(() => console.log("D"));
process.nextTick(() => console.log("C"));
console.log("A");
console.log("B");
Terminal: node app.js
A
B
C
D
E
- A and B are the program's own lines. Then the nextTick queue gives C, the promise gives D, and the timer, in the loop, gives E, even though it was set first.
The order is A, B, C, D, E.
Check: Move the setTimeout to the last line: the order stays the same.
A path that fails: reading the lines from top to bottom: E, D, C, A, B. The order of writing is not the order of running.
When you are stuck: the output comes in an order you did not expect
Mark each line: your code, nextTick, promise, timer, immediate, I/O.
Your code runs first, all of it; then nextTick, then promises; then the loop's phases.
If a timer runs very late, look for a long loop or a big sum in your code: it keeps the engine busy.
Your turn
node -e 'setTimeout(() => console.log(2), 0); console.log(1)'
What does this print? Say your answer aloud first, then press Run or tap to reveal.Tap to reveal
1
2
- The program's own line runs first.
- The timer waits for the loop.
It prints 1, then 2.
Which runs first after your code: a promise's then callback, or a process.nextTick callback?Tap to reveal
- Look at the table of steps.
process.nextTick.
Why does await wait(2000) not stop the whole program for two seconds?Tap to reveal
- What does the engine do while the timer waits?
The function steps aside, and the engine runs other jobs until the promise resolves.
Did you know?
libuv, the loop under Node
Node's event loop comes from a library of its own. The libuv documentation calls it a multi-platform support library with a focus on asynchronous input and output, primarily developed for use by Node.js. Other projects use it too, such as the language Julia and uvloop for Python. So the loop that runs Node's callbacks is libuv's.
Why it fits here: It names the machinery behind this topic's event loop: libuv, a library made for Node.js.
Source: libuv documentation
Four threads behind the scenes
Your JavaScript runs on one thread, but Node is not only one thread. The libuv documentation says it keeps a thread pool for work such as file system operations, with a default size of 4 threads, changeable at startup with UV_THREADPOOL_SIZE up to 1024. The Node manual adds that all fs APIs other than file watchers, and some crypto APIs, use that pool.
Why it fits here: It answers this topic's question: JavaScript runs on one thread, while file work goes to libuv's pool of 4 threads.
Sources: libuv documentation: Thread pool work scheduling; Node.js manual: Command-line options
In one line
Node runs your code to its end, then the nextTick queue, then the promise callbacks, then the event loop's phases: timers, I/O, setImmediate. Waiting work is handed off, so the engine never stops; only code that never steps aside blocks it.
Where it is used
Node runs a great deal of the software you meet without seeing it. Here is where each idea of this lesson does its work.
| What you learned | Where it is used | A real example |
|---|---|---|
| a JavaScript runtime outside the browser | servers, command-line tools, build tools | the program that answers a website's requests |
| node app.js | starting any Node program | starting a shop's server on a cloud machine |
| standard output and standard error | logs that are saved and searched | results to a file, warnings to the screen |
| process.argv | command-line tools | a tool run as node resize.js photo.jpg 800 |
| process.env | settings and secrets kept out of the code | a server's port, or a database password, set by the machine |
| exit codes | scripts, build tools and tests | a test run that fails the build with the exit code 1 |
| the event loop | a server that serves many people at once | one Node program answering thousands of requests |
The last row is the reason Node exists. A server spends most of its time waiting: for a file, a database, another machine. Because Node hands that waiting off and takes the next job, one Node program can serve many people at once, as the Engine Hall's one engine serves a whole hall.
Mistakes and debugging
These are the slips that people meet most often in their first Node programs. Every output below is the real one, from the code shown.
1. Using the page in Node
app.js
console.log(document.title);
Terminal: node app.js
echo "[$?]"
/home/asha/shop/app.js:1
console.log(document.title);
^
ReferenceError: document is not defined
at Object.<anonymous> (/home/asha/shop/app.js:1:13)
at Module._compile (node:internal/modules/cjs/loader:1781:14)
at Object..js (node:internal/modules/cjs/loader:1913:10)
at Module.load (node:internal/modules/cjs/loader:1505:32)
at Function._load (node:internal/modules/cjs/loader:1309:12)
at wrapModuleLoad (node:internal/modules/cjs/loader:254:19)
at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:171:5)
at node:internal/main/run_main_module:36:49
Node.js v22.23.1
[1]
There is no page in Node. The fix: work on values and print them with console.log; keep page code for the browser.
2. Treating an argument as a number
app.js
const count = process.argv[2];
console.log(count * 2, count + 2);
Terminal: node app.js 5
10 52
The * turned the string 5 into a number, but + joined two strings, giving 52. The fix: const count = Number(process.argv[2]); once, at the start.
3. Leaving with process.exit while work waits
app.js
setTimeout(() => console.log("saved"), 100);
process.exit(0);
Terminal: node app.js
echo "[$?]"
[0]
The timer never ran, and nothing says so. The fix: set process.exitCode, and let the program end by itself when its work is done.
4. Reading argv from index 0
app.js
console.log("shift:", process.argv[0]);
Terminal: node app.js night
shift: /usr/bin/node
Index 0 is the path of node, and index 1 the file's. The fix: process.argv[2], or process.argv.slice(2) for all the words you typed.
5. Expecting a timer to run while code is still busy
app.js
setTimeout(() => console.log("the 10 ms timer"), 10);
let n = 0;
for (let i = 0; i < 5e6; i++) n += i % 7;
console.log("the long sum is done:", n);
Terminal: node app.js
the long sum is done: 14999995
the 10 ms timer
However long the sum takes, the timer waits for it, as the engine waits for the clerk's sum in the story. The fix: keep each piece of work short, and hand long waits to Node's asynchronous tools, with callbacks or await.
The debugging corner: what is the program doing?
The line console.log(process.argv) shows exactly what the program was given, and echo $? right after a run shows how it ended. The redirections 2>/dev/null and > file separate the two streams. Numbering your log lines, as in the event loop section, shows the order in which things really ran.
Quick card
The whole lesson on one card. Come back to it whenever you need a reminder.
app.js
const [shift = "day"] = process.argv.slice(2); // the words after the file
console.log("shift:", shift, "home:", process.env.HOME);
console.error("a warning goes to standard error");
setTimeout(() => console.log("3: a timer, in the loop"), 0);
Promise.resolve().then(() => console.log("2: a promise, after the code"));
console.log("1: the code runs first");
if (shift === "none") process.exitCode = 1; // the exit code, read with $?
Terminal: node app.js night 2>/dev/null; echo "[$?]"
shift: night home: /home/asha
1: the code runs first
2: a promise, after the code
3: a timer, in the loop
[0]
| When you see | It means | Do |
|---|---|---|
Cannot find module '/home/asha/shop/x.js' | no file by that name, there | check the name and the folder |
document is not defined | page code in Node | print with console.log instead |
31 where you expected 4 | an argument used as a string | Number(process.argv[2]) |
undefined from process.env | the variable is not set | set it, as in NAME=value node app.js |
exit status 1 after a report | an error that nothing caught | read the line under the caret |
| a timer that runs late | the engine was busy with your code | make the work shorter, or hand it off |
The story: The engine runs again
You learn the engine's ways one by one: how to start it with a file, how it speaks and how it reports trouble, and how it reads the orders it is given. Then you learn its board of jobs, kept in strict order, with the waiting ones handed off so that it never stands still.
The long sum goes to the runners in small pieces. The engine turns again, and the whole hall breathes.
The Foreman chalks your name on the board of keepers. "Tomorrow," she says, "we build a machine from parts."
Reagents gathered: Node.js, runtime, process, exit code, event loop, callback.
Sources
- The Node.js documentation (Not stated for the docs in the Node.js LICENSE file (read 2026-10-26); facts and ideas only)
- MDN Web Docs (Prose CC BY-SA 2.5 or later; code samples added since 2010-08-20 CC0 (its licensing page, read 2026-10-26); reused with credit)