Node.js Fundamentals: Running Programs, Arguments, Environment, Life Cycle and Modules
Start writing server-side JavaScript: what Node is (V8 plus libuv), versions and LTS, running scripts, stdout vs stderr, process.argv and util.parseArgs, environment variables and .env files, life cycle, exit codes, signals, fatal errors, CommonJS vs ES modules, require(esm) and npm.
kvi5hnuCode Sprout team member9 min readOn this page
Node.js runs JavaScript outside the browser: web servers and APIs, command-line tools, build systems (most of the front-end toolchain runs on Node), scripts and desktop apps. It combines Google's V8 engine, the same one in Chrome, with libuv, a C library that provides an event loop and non-blocking access to files, networks and processes, plus a large standard library of built-in modules. This part of the course covers Node's core APIs; this article covers the basics every Node program relies on.

Versions and running code
Node has a new major version every year or so, and even-numbered versions become Long-Term Support (LTS) releases, supported for about 30 months. As of late 2026, Node 22, 24 and 26 are supported LTS lines, with 26 the "active" LTS since October 2026, and production servers should run an LTS version. Starting with Node 27, Node moves to one major release per year. The examples in this course were run on Node 25.
The common ways to run code:
node app.js # run a file
node # interactive REPL (article 2)
node -e "console.log(1 + 1)" # evaluate a string; -p prints the result
node --watch app.js # restart automatically when files change
node --run test # run a package.json script without npm
node app.ts # TypeScript: types are stripped, then the code runs
Running .ts files directly works in current Node versions through type stripping: Node removes type annotations without checking them. Type checking still needs the TypeScript compiler (Part 17).
Output: stdout and stderr
In a browser, console.log is a debugging aid. In Node, it's the standard way for a program to print output: it writes to stdout (standard output). console.error and console.warn write to stderr (standard error). Keeping the two separate matters for command-line tools: when a user redirects output with node report.js > out.csv, data goes to the file while errors still appear on the screen. For lower-level control, process.stdout.write(text) writes without adding a newline.
Command-line arguments
process.argv is an array of strings: the absolute path of the node executable, the absolute path of the script, then the arguments the user typed after the script name. Options meant for Node itself, such as --watch, are consumed by Node and don't appear.
$ node greet.js --name Ada -v notes.txt
process.argv -> [ '/usr/local/bin/node', '/home/ada/greet.js', '--name', 'Ada', '-v', 'notes.txt' ]
Parsing flags by hand gets messy quickly. The built-in util.parseArgs handles long and short options, booleans, defaults and positional arguments:
const { parseArgs } = require("node:util");
// In a real program, omit `args` and parseArgs reads process.argv.slice(2)
const { values, positionals } = parseArgs({
args: ["--port", "8080", "-v", "report.csv", "summary.csv"],
options: {
port: { type: "string", default: "3000" },
verbose: { type: "boolean", short: "v", default: false },
output: { type: "string", short: "o" },
},
allowPositionals: true,
});
console.log(values.port, Number(values.port) + 1, values.verbose, values.output);
console.log(positionals);
try {
parseArgs({ args: ["--colour"], options: { color: { type: "boolean" } } });
} catch (err) {
console.log(err.code);
}
8080 8081 true undefined
[ 'report.csv', 'summary.csv' ]
ERR_PARSE_ARGS_UNKNOWN_OPTION
Option values are strings, so convert them, as with Number(values.port). Unknown options throw an error, unless you pass strict: false. Larger CLI tools often use packages such as commander or yargs, which add help text and subcommands.
Environment variables
process.env holds the environment variables the program was started with, such as PATH, HOME and anything set for configuration (PORT, DATABASE_URL, NODE_ENV). Like arguments, they're always strings:
// Environment variables are always strings (or undefined)
process.env.MAX_ITEMS = 25; // assigning converts to a string
console.log(typeof process.env.MAX_ITEMS, process.env.MAX_ITEMS);
function config(env) {
return {
port: Number.parseInt(env.PORT ?? "3000", 10),
debug: env.DEBUG === "1" || env.DEBUG === "true",
mode: env.NODE_ENV ?? "development",
};
}
console.log(config({}));
console.log(config({ PORT: "8080", DEBUG: "true", NODE_ENV: "production" }));
string 25
{ port: 3000, debug: false, mode: 'development' }
{ port: 8080, debug: true, mode: 'production' }
Collecting configuration in one function with defaults and conversions, rather than reading process.env all over the code, makes the program easier to test and to reason about.
For local development, settings are often kept in a .env file (PORT=8080, one per line). Node can load it without any package, with node --env-file=.env app.js or by calling process.loadEnvFile(".env") at startup. Never commit .env files that contain secrets.
The program life cycle
Node runs the main file from top to bottom. Then, instead of exiting, it keeps running its event loop as long as anything is pending: timers, open servers or sockets, file operations, child processes. A web server therefore runs forever, because it's always waiting for connections, while a script that only computes something exits as soon as its last callback finishes.
When nothing is left, Node emits beforeExit on process. A listener can schedule more work, which keeps the program alive, and beforeExit fires again when that's done. Finally exit fires, and only synchronous code can run in exit listeners:
let rounds = 0;
process.on("beforeExit", () => {
console.log("beforeExit: nothing left to do");
if (rounds++ === 0) setTimeout(() => console.log("one more task, scheduled from beforeExit"), 5);
});
process.on("exit", (code) => console.log(`exit with code ${code}`));
setTimeout(() => console.log("timer fired"), 10);
console.log("end of main script");
end of main script
timer fired
beforeExit: nothing left to do
one more task, scheduled from beforeExit
beforeExit: nothing left to do
exit with code 0
Exit codes
A process reports an exit code to whoever started it: 0 means success, and anything else signals failure, which shells and CI systems check. Set process.exitCode = 1 to fail while letting pending work finish, or call process.exit(1) to stop immediately, abandoning pending writes and callbacks. Prefer exitCode unless you really need to stop at once.
Signals and graceful shutdown
Pressing Ctrl-C sends the SIGINT signal, and process managers and containers send SIGTERM when stopping a service. By default, Node exits. Servers usually handle these signals to shut down cleanly:
process.on("SIGTERM", shutdown);
process.on("SIGINT", shutdown);
function shutdown(signal) {
console.error(`${signal} received: closing`);
server.close(() => { // stop accepting connections, finish current requests
database.end().then(() => process.exit(0));
});
setTimeout(() => process.exit(1), 10_000).unref(); // give up after 10 s
}
unref() tells Node not to keep the process alive just for that timer.
Uncaught errors
An exception that nothing catches prints a stack trace and ends the program with a nonzero exit code. The same applies to unhandled promise rejections: since Node 15, a rejected promise with no handler is fatal by default. This is safer than continuing in an unknown state.
Global handlers exist (process.on("uncaughtException", ...) and process.on("unhandledRejection", ...)), but they should only log the problem and exit. Resuming after an unexpected error can leave files, connections or data half-updated. The right fix is local error handling (article 96): try/catch around await, .catch() on promises, and error listeners on event emitters (article 125).
Modules in Node
Node supports both module systems covered in articles 74–76:
- CommonJS:
require()andmodule.exports. This is Node's original system, still used by most npm packages. - ES modules:
importandexport, the JavaScript standard.
Node decides how to load each file:
| File | Loaded as |
|---|---|
.mjs | ES module |
.cjs | CommonJS |
.js with "type": "module" in the nearest package.json | ES module |
.js with "type": "commonjs", or no type field | CommonJS, unless the file contains import/export syntax, in which case current Node versions detect it and load it as an ES module |
New projects should usually set "type": "module" and use ES modules. Some practical points:
- ES modules can
importCommonJS modules. - In current Node versions (22.12 and later, and 20.19), CommonJS code can also
require()an ES module, as long as that module doesn't use top-levelawait. The result is the module's namespace object,{ answer: 42, default: [Function] }. Older Node versions threw an error here, and you'll still see that described in older documentation. - Built-in modules are imported with the
node:prefix:import { readFile } from "node:fs/promises". In CommonJS code,require("node:fs"). - CommonJS's
__dirnameand__filenamedon't exist in ES modules; useimport.meta.dirnameandimport.meta.filename.
Built-in batteries: SQLite and the permission model
Recent Node versions ship features that used to need packages or other tools:
node:sqliteis a built-in SQLite database, with synchronous prepared statements. It's good for local tools, tests, caches and small apps:
const { DatabaseSync } = require("node:sqlite");
const db = new DatabaseSync(":memory:"); // or a file path such as "app.db"
db.exec("CREATE TABLE books (id INTEGER PRIMARY KEY, title TEXT NOT NULL, year INTEGER)");
const insert = db.prepare("INSERT INTO books (title, year) VALUES (?, ?)");
insert.run("Structure and Interpretation", 1985);
insert.run("The Pragmatic Programmer", 1999);
insert.run("Refactoring", 1999);
// Placeholders keep values out of the SQL text, which prevents SQL injection
const byYear = db.prepare("SELECT id, title FROM books WHERE year = ? ORDER BY title");
console.log(byYear.all(1999).map((row) => `${row.id}: ${row.title}`));
console.log(db.prepare("SELECT COUNT(*) AS n FROM books").get().n);
db.close();
[ '3: Refactoring', '2: The Pragmatic Programmer' ]
3
- The permission model restricts what a script may touch. Run with
node --permission app.jsand file system access, child processes, worker threads and network access are denied unless granted:--allow-fs-read=./data,--allow-fs-write=./out,--allow-child-process,--allow-worker,--allow-net. A denied call throws an error with codeERR_ACCESS_DENIED, andprocess.permission.has("fs.read", path)checks access in advance. It's a seatbelt against bugs and compromised dependencies, not a full sandbox for hostile code. - Other built-ins covered later:
node --watch(restart on changes),--env-file(see "Environment variables" above),node:test(article 134) and running TypeScript files directly (article 138).
npm and package.json
Node ships with npm, the package manager for the npm registry, which hosts millions of packages. A project's package.json records its name, version, module type, dependencies and scripts:
npm init -y # create package.json
npm install express # add a dependency (into node_modules/, recorded in package.json)
npm install -D vitest # add a development-only dependency
npm run test # run a script defined in package.json "scripts"
npx some-tool # run a package's command without installing it globally
The generated package-lock.json records the exact version of every installed package. Commit it, so everyone, including your CI server, installs identical dependencies with npm ci. Part 17 covers package management and other tools in more depth.
Common questions
Why does my Node script never exit?
Something is keeping the event loop alive: an open server or socket, a database connection, a setInterval, or a stream that was never closed. Close those resources when you're done, or call unref() on timers that shouldn't keep the process running.
Why is process.env.PORT + 1 equal to "30001"?
Environment variables are strings, so + concatenates. Convert first: Number(process.env.PORT) + 1.
Should I use CommonJS or ES modules?
ES modules for new code: they're the standard, work in browsers too, and support top-level await. CommonJS remains common in existing projects, and the two can now load each other in both directions in current Node versions.
Where's window or document in Node?
They don't exist: Node has no page. The global object is globalThis, with Node-specific globals such as process and Buffer, plus web-compatible ones such as fetch, URL, TextEncoder, AbortController, structuredClone and setTimeout.
Summary
- Node = V8 + libuv + built-in modules. Use an LTS version in production.
console.logwrites to stdout andconsole.errorto stderr. Arguments are inprocess.argv(useutil.parseArgs), and configuration comes fromprocess.env(always strings;--env-fileloads.envfiles).- A program runs its main file, then keeps running while work is pending;
beforeExitandexitevents mark the end. Useprocess.exitCodefor failure codes, handleSIGINT/SIGTERMfor graceful shutdown, and remember that uncaught exceptions and unhandled rejections are fatal. - Files load as CommonJS or ES modules based on the extension,
package.json"type"and syntax detection. Import built-ins withnode:. Current Node canrequire()ES modules. - npm manages dependencies in
package.jsonandpackage-lock.json.
Practice Questions
Running node tool.js --dry-run input.txt, what is process.argv.slice(2)?
Answer
[ '--dry-run', 'input.txt' ]. The first two elements are the paths of the Node executable and the script.
This server never starts listening on port 8081. Why?
const port = process.env.PORT || 8080;
server.listen(port + 1);
Answer
If PORT is set to "8080", then port + 1 is the string "80801", because environment variables are strings. Convert it first: Number(process.env.PORT ?? 8080) + 1.
What's the difference between process.exitCode = 1 and process.exit(1)?
Answer
process.exitCode = 1 sets the code that will be reported when the program ends naturally, so pending work such as writing output still completes. process.exit(1) ends the process immediately and abandons any pending asynchronous work.
A project's package.json has "type": "module". How do you write one file in CommonJS anyway?
Answer
Give it the .cjs extension. The extension overrides the type field, so the file uses require and module.exports.
Previous: Example: A Parallel Mandelbrot Explorer with Workers and Canvas, plus Other Browser APIs
Next: Asynchronous Node: Callbacks, Promises, Sync APIs and the Event Loop Phases

More in JavaScript Course
Quiz: Modern JavaScript, ES2022 to ES2027 Features
Twenty-four questions on what's new in JavaScript: change-array-by-copy methods, groupBy, Set methods, iterator helpers, Promise.withResolvers and Promise.try, RegExp.escape and the v flag, using declarations, Error.isError, Base64 typed arrays, Temporal, getOrInsert and Iterator.zip.
Quiz: JavaScript's Delicate Details (Spec-Level Edge Cases)
Twenty-eight questions on the fine print of JavaScript, drawn from the ECMAScript specification and MDN: sparse arrays, -0, number limits, JSON edge cases, Date overflow, UTF-16, property attributes, inherited accessors, comparison quirks, labels, regex state and Symbol.toPrimitive.
Quiz: JavaScript Interview Questions (Output Prediction and Core Concepts)
Thirty classic JavaScript interview questions: closures in loops, hoisting and the TDZ, this, the event loop and microtasks, async/await, coercion, sorting and parseInt traps, prototypes, copying, finally, generators and bind. Every answer was verified by running it.
Quiz: JavaScript Course Final Exam (All 17 Parts)
The final exam for the JavaScript course: thirty questions spanning all seventeen parts, from syntax, types and operators through objects, arrays, functions, classes, modules, the standard library, iterators, async code, metaprogramming, browsers, Node.js and tooling.
Discussion
Sign in to ask a question or share what you learned.