Sub topic 4
Running JavaScript with Node.js
This chapter assumes you can write basic JavaScript (variables, functions, objects, arrays), you have used promises or callbacks, and you are comfortable typing commands in a terminal. It also assumes Node.js 20 or later is installed. Check your version with node --version. The built-in modules (fs, path, http) and the details of ES modules versus CommonJS come in later chapters. Here the focus is the node command itself: how it starts, how it runs your code, how it receives input from the command line, and how it decides to stop.
The `node` command at a glance
Node.js combines the V8 engine with a set of host APIs for files, processes, and networking. There is no page and no DOM. Your entry point is a file path or an inline string given to the node executable. There are four common ways to start it:
| Invocation | What happens |
|---|---|
| `node` | Starts the interactive REPL |
| `node app.js` | Runs the file `app.js`, then exits when no work remains |
| `node -e "code"` | Evaluates the string as a script |
| `node -p "expr"` | Evaluates the expression and prints its result |
The difference between -e and -p trips people up. node -e "1 + 2" prints nothing, because the result is computed and then thrown away. node -p "1 + 2" prints 3. Use -p for quick calculations such as node -p "process.versions.v8".
The REPL
REPL stands for Read-Eval-Print Loop. Run node with no arguments and you get a > prompt. Node reads each line, evaluates it, and prints the result.
$ node
Welcome to Node.js v22.11.0.
Type ".help" for more information.
> const nums = [3, 1, 2]
undefined
> nums.sort()
[ 1, 2, 3 ]
> _.length
3
> await Promise.resolve('done')
'done'
> .exitA few REPL-specific features are worth knowing:
_holds the result of the last expression, and_errorholds the last thrown error.- Top-level
awaitworks at the prompt, which makes it handy for trying out promise-based APIs. - Built-in modules are preloaded as globals. Typing
fs.existsSync('.')works without an import. - Dot commands control the session.
.helplists them,.editoropens a multi-line mode (finish with Ctrl+D),.load file.jsruns a file into the current session, and.save file.jswrites your session to disk. - Ctrl+C cancels the current line, a second Ctrl+C exits, and Ctrl+D exits immediately.
Running a script file
Create hello.js:
// hello.js (run with: node hello.js Ada)
const name = process.argv[2] ?? 'world';
console.log(`Hello, ${name}!`);node hello.js Ada
# Hello, Ada!
node hello.js
# Hello, world!Node resolves the path relative to the current working directory, reads the file, and runs it as a module. That one fact has consequences browser developers often miss. Top-level const and let declarations are scoped to the file and do not become globals. Inside your code, process.cwd() is the directory you ran the command from, which may differ from the directory the script lives in. Running node scripts/hello.js from the project root gives process.cwd() as the root.
The lifecycle of a Node.js process
A browser tab stays open until the user closes it. A Node.js process exits as soon as it has nothing left to do. After your top-level code finishes, Node keeps running only while something is pending: a timer, an open server socket, an in-flight file read, or a listener on process.stdin.
You can watch this happen:
// lifetime.js
process.on('exit', (code) => {
console.log(`exiting with code ${code}`);
});
let ticks = 0;
const id = setInterval(() => {
ticks += 1;
console.log('tick', ticks);
if (ticks === 3) clearInterval(id);
}, 200);
console.log('top-level code finished');The output is top-level code finished, then three ticks, then exiting with code 0. If you remove the clearInterval call, the process never exits, because the interval keeps the event loop alive. Calling id.unref() tells Node that a timer alone should not keep the process running.
Command-line arguments
Reading `process.argv`
process.argv is an array of strings:
- Index 0 is the absolute path to the
nodeexecutable. - Index 1 is the absolute path to the script.
- Index 2 and later are the arguments the user typed after the script name.
// args.js
console.log('argv:', process.argv);
console.log('user args:', process.argv.slice(2));
console.log('node options:', process.execArgv);node --trace-warnings args.js build --verbose 3argv: [ '/usr/local/bin/node', '/home/ada/args.js', 'build', '--verbose', '3' ]
user args: [ 'build', '--verbose', '3' ]
node options: [ '--trace-warnings' ]Position matters. Options before the script name go to Node and appear in process.execArgv. Everything after the script name goes to your program, even if it looks like a Node flag. Every argument is a string, so '3' must be converted with Number() before you do arithmetic with it.
Parsing options with `util.parseArgs`
Slicing process.argv by hand breaks down once you have flags with values, short aliases, and defaults. Node includes a parser, parseArgs from node:util, which is stable from Node 20. The example below uses the .mjs extension so that import works. The modules chapter explains why.
// greet.mjs (run with: node greet.mjs Ada --shout -t 2)
import { parseArgs } from 'node:util';
const { values, positionals } = parseArgs({
options: {
shout: { type: 'boolean', short: 's' },
times: { type: 'string', short: 't', default: '1' },
},
allowPositionals: true,
});
const name = positionals[0] ?? 'world';
const count = Number(values.times);
for (let i = 0; i < count; i++) {
const line = `Hello, ${name}!`;
console.log(values.shout ? line.toUpperCase() : line);
}node greet.mjs Ada --shout -t 2
# HELLO, ADA!
# HELLO, ADA!By default parseArgs runs in strict mode. An unknown flag such as --colour throws a TypeError with code ERR_PARSE_ARGS_UNKNOWN_OPTION, which catches typos instead of ignoring them. Option values are still strings unless the type is boolean, so the Number() conversion is still your job.
Exit codes and errors
The shell reads a process's exit code to decide whether it succeeded: 0 means success, and any other value means failure. CI pipelines and && chains depend on this.
// check-age.js
const age = Number(process.argv[2]);
if (!Number.isInteger(age) || age < 0) {
console.error('Usage: node check-age.js <age>');
process.exitCode = 2;
} else {
console.log(age >= 18 ? 'adult' : 'minor');
}node check-age.js abc; echo $?
# Usage: node check-age.js <age>
# 2Setting process.exitCode is better than calling process.exit(). process.exit() stops the process at once and skips any pending asynchronous work. On some platforms that includes output still being written to a pipe, so part of your log can disappear. Setting exitCode lets the process finish its work and then exit with your code.
Node also sets exit codes for you:
| Situation | Default behavior |
|---|---|
| Script finishes normally | Exit code 0 |
| Uncaught exception | Prints stack trace, exit code 1 |
| Unhandled promise rejection | Treated as an uncaught exception, exit code 1 (Node 15 and later) |
| Syntax error in the entry file | Prints the error location, exit code 1 |
| `process.exitCode = n` | Exits with `n` once work is done |
Useful flags for daily work
| Flag | Purpose |
|---|---|
| `--watch` | Restart the script when it or its imports change (stable in Node 22) |
| `--env-file=.env` | Load environment variables from a file into `process.env` (Node 20.6 and later) |
| `--inspect` | Open a debugger port (covered in the debugging chapter) |
| `--trace-warnings` | Print stack traces for process warnings |
| `-r` / `--import` | Preload a CommonJS or ES module before the entry script |
For example, node --watch --env-file=.env server.js gives you a development loop with configuration loaded and automatic restarts. You no longer need a third-party tool for that.
Making a script executable
On macOS and Linux you can run a script directly by adding a shebang line and setting the execute permission. A shebang is a first line beginning with #! that tells the operating system which interpreter to use.
#!/usr/bin/env node
// now.js
console.log(new Date().toISOString());chmod +x now.js
./now.js
# 2026-11-24T11:20:08.903ZNode ignores the shebang line, so the same file still works with node now.js and on Windows, which does not honor shebangs. The npm bin field uses this mechanism to install command-line tools. The packaging chapter covers that.
Common errors
- Off-by-one on
argv. The first user argument isprocess.argv[2], not[0]. - Flags in the wrong place. In
node app.js --watch, the--watchflag goes to your app and Node ignores it. Writenode --watch app.js. - Treating arguments as numbers.
process.argv[2] + 1with input5gives'51'. - Confusing
cwdwith script location. Relative paths in file operations resolve againstprocess.cwd(). The built-ins chapter shows how to resolve paths relative to the script. - A process that never exits. A forgotten interval, open server, or stdin listener keeps the event loop alive.
- Using
process.exit()to signal failure. It can cut off output. Setprocess.exitCodeinstead.
Exercise
You run node --watch app.js --port 8080. What are process.argv.slice(2) and process.execArgv, and does Node's watch mode turn on?
Show answer
process.argv.slice(2) is ['--port', '8080'] and process.execArgv is ['--watch']. Watch mode is on, because --watch comes before the script name and so goes to Node.
Exercise
A script ends with setInterval(poll, 5000) and you want it to exit as soon as its other work is finished, even if the interval is still scheduled. What is the smallest change?
Show answer
Keep the timer handle and call unref() on it: setInterval(poll, 5000).unref(). An unref'd timer does not keep the event loop alive, so the process exits once no other work is pending.
Exercise
Write a one-line command that prints the number of CPU cores Node.js reports, and explain why node -e with the same expression prints nothing.
Show answer
node -p "require('node:os').availableParallelism()" (or os.cpus().length) prints the number. -p prints the value of the expression. -e only evaluates it and throws the result away, so you would need an explicit console.log(...).
Exercise
Change check-age.js so that it exits with code 1 when no argument is given and code 2 when the argument is given but is not a valid age. Do not use process.exit().
Show answer
Check process.argv.length < 3 first. In that case, print the usage message with console.error and set process.exitCode = 1. Otherwise convert the argument with Number(). If it is not a non-negative integer, set process.exitCode = 2. If it is valid, print adult or minor. Because none of these branches calls process.exit(), the output always finishes writing before the process exits.