Sub topic 4
Running JavaScript with Node.js
This chapter assumes you know basic JavaScript syntax, can open a terminal, and have installed Node.js 18 or later. Running node --version should print a version number such as v22.11.0.
Node.js is a runtime. It pairs the V8 engine with its own host APIs for files, processes, and networking. A web page runs your code when it loads an HTML file. Node.js runs your code when you call the node command.
Three ways to run code
| Command | What it does |
|---|---|
| `node` | Starts the REPL, an interactive prompt |
| `node file.js` | Runs a script file |
| `node -e "code"` or `node -p "expr"` | Runs a one-liner; `-p` also prints the result |
The REPL
REPL stands for read-eval-print loop. Each line you type is evaluated and its result is printed right away. It works well for checking how an API behaves.
$ node
> 2 ** 10
1024
> _ * 2
2048
> [1, 2, 3].map(n => n * n)
[ 1, 4, 9 ]
> .exitThe _ variable holds the last result. Press Tab to autocomplete property names. Type .help to list the REPL commands. To leave, type .exit or press Ctrl+D.
Running a script
Save this file and run node hello.js Ada:
// hello.js (run with: node hello.js Ada)
const name = process.argv[2] ?? 'world';
console.log(`Hello, ${name}!`);It prints Hello, Ada!. If you run it without an argument, it prints Hello, world!.
Reading command-line arguments
process.argv is an array of strings. Node.js fills it in before your code runs.
Your own arguments start at index 2, so most scripts begin with process.argv.slice(2). Every entry is a string, which means node add.js 2 3 gives you '2' and '3', not numbers.
For flags such as --verbose or --name=Ada, use the built-in parseArgs instead of writing your own parser:
// greet.mjs (run with: node greet.mjs --name Ada --shout)
import { parseArgs } from 'node:util';
const { values } = parseArgs({
options: {
name: { type: 'string', default: 'world' },
shout: { type: 'boolean', default: false },
},
});
let message = `Hello, ${values.name}!`;
if (values.shout) message = message.toUpperCase();
console.log(message);Exit codes
Shells and CI systems use a process's exit code to tell success from failure. Code 0 means success. Anything else means failure. An uncaught exception exits with code 1. To report failure yourself, set process.exitCode:
// check.js
const input = process.argv[2];
if (input === undefined) {
console.error('usage: node check.js <value>');
process.exitCode = 1;
} else {
console.log(`got ${input}`);
}Prefer process.exitCode to process.exit(1). Calling process.exit() ends the process immediately, so output that is still buffered and pending asynchronous work can be lost.
Common errors
Cannot find module '/path/hello.js': you rannodefrom the wrong directory. Relative script paths resolve against the current working directory.ReferenceError: document is not defined: browser APIs do not exist in Node.js.- Doing math on arguments without converting them:
'2' + '3'is'23'. UseNumber()first.
Exercise
Write sum.js so that node sum.js 4 5 6 prints 15, and so that it prints an error and exits with code 1 if any argument is not a number.
Show answer
const nums = process.argv.slice(2).map(Number); if (nums.length === 0 || nums.some(Number.isNaN)) { console.error('usage: node sum.js <numbers...>'); process.exitCode = 1; } else { console.log(nums.reduce((a, b) => a + b, 0)); }
Exercise
You run node -p "process.argv.length". What does it print, and why?
Show answer
It prints 1. With -p (or -e) there is no script file, so process.argv contains only the path to the node executable.