The Node.js runtime
Run a Node.js script
Create a JavaScript file, execute it with Node, read its output, and interpret a non-zero exit status.
8 minute lesson
Create hello.js:
const name = process.argv[2]
if (!name) {
console.error('Usage: node hello.js <name>')
process.exitCode = 1
} else {
console.log(`Hello, ${name}`)
}
Run it from a terminal:
node hello.js Ada
The shell starts a new Node.js process. Node reads the entry file, decides which module system it uses, evaluates its top-level code, and keeps the process alive while referenced timers, servers, sockets, or other work remain. This script has no pending work, so it exits after printing.
process.argv contains the Node executable, the entry-script path, and then the arguments supplied by the user. Here the first user argument is at index 2.
Paths passed by your code are often resolved from the terminal’s current working directory, which can differ from the directory containing the script. Print both when diagnosing a path mistake:
console.log({ cwd: process.cwd(), script: process.argv[1] })
Successful programs conventionally exit with status 0; a non-zero status tells a shell, CI job, or another process that the command failed. console.error() writes the explanation to standard error. Setting process.exitCode = 1 lets pending output and normal cleanup finish before Node exits.
Avoid calling process.exit() for ordinary validation failures because it can terminate before asynchronous output is flushed. Syntax errors, missing modules, and uncaught exceptions already make Node exit non-zero.
Your action is to run the script once with a name and once without one. Inspect both output streams and confirm that the second command returns a non-zero status in your shell.
Lesson completed