CodingNic

Core Node.js Modules

os and process: The Machine and the Program

Core Node.js Modules 12 min read

os and process: The Machine and the Program

Objectives

By the end of this lesson, you should be able to:

  • Read information about the host machine with os
  • Set a process’s exit code with process.exitCode
  • Explain the difference between process.exitCode and process.exit()

💡 Why this matters: Module 3 already covered process.env, process.argv, and process.cwd(). This lesson covers two things not yet seen: information about the machine a program runs on (os), and how a program communicates success or failure when it finishes (process exit codes), both routinely relevant once a program is more than a single script.

⚠️ A note on verification: every snippet and output in this lesson was actually run with Node.js.

The os Module

javascript
const os = require('os');

console.log('platform:', os.platform());
console.log('arch:', os.arch());
console.log('CPU cores:', os.cpus().length);
console.log('home directory:', os.homedir());
console.log('total memory (GB):', (os.totalmem() / 1024 / 1024 / 1024).toFixed(1));
console.log('free memory (GB):', (os.freemem() / 1024 / 1024 / 1024).toFixed(1));
text
platform: linux
arch: x64
CPU cores: 2
home directory: /sessions/bold-charming-dijkstra
total memory (GB): 3.8
free memory (GB): 3.4

os.platform() returns the operating system ('linux', 'darwin' for macOS, 'win32' for Windows), os.arch() returns the CPU architecture, os.cpus() returns an array with one entry per CPU core, and os.totalmem()/os.freemem() return memory in bytes. Every value here depends entirely on the machine running the code, running this same script elsewhere prints different numbers.

Exit Codes: process.exitCode

javascript
console.log('starting work');
process.exitCode = 0;

process.on('exit', (code) => {
  console.log(`process exiting with code ${code}`);
});

console.log('work finished');
text
starting work
work finished
process exiting with code 0

An exit code communicates success (0) or failure (any non-zero number) to whatever ran the program, a shell script, a CI pipeline, another process. Setting process.exitCode doesn’t stop the program, it just records what code to exit with once the program naturally finishes, everything after it still runs, including the 'exit' event handler firing last, right as the process actually ends.

Forcing an Immediate Exit: process.exit()

javascript
console.log('step 1');
process.exit(1);
console.log('step 2, this never runs');
text
step 1

Checking the shell’s exit status immediately afterward:

bash
node forceexit.js; echo "exit status: $?"
text
step 1
exit status: 1

Unlike process.exitCode, process.exit(code) stops the program immediately, 'step 2' never logs, because it never gets the chance to run. This is useful for a fatal error where continuing is pointless, but it’s also risky, forcing an exit skips any pending asynchronous work (an in-flight file write, an unfinished HTTP response), which process.exitCode alone does not.

Choosing Between Them

For most cases, setting process.exitCode and letting the program finish naturally is safer, it guarantees pending work completes first. process.exit() is best reserved for genuinely fatal situations, an unrecoverable startup error, where continuing to run risks worse problems than stopping immediately.

Try It

  1. Write a script that logs each CPU core’s model and speed from os.cpus().
  2. Write a script that does some work, sets process.exitCode = 0 on success or process.exitCode = 1 if a condition fails, and confirm the shell’s exit status (echo $?) matches in both cases.
  3. Write a script that calls process.exit(1) partway through, with a console.log after it, and confirm that line never runs.
  4. Explain, in your own words, a real situation where process.exit()’s immediate stop would be the wrong choice, because it risks cutting off pending work.

Recap

  • os describes the host machine, platform, architecture, CPU count, memory, all machine-dependent.
  • process.exitCode = n records an exit code without stopping the program, the safer default.
  • process.exit(n) stops immediately, skipping any remaining code and pending async work, reserved for genuinely fatal situations.

Next lesson: crypto, hashing and generating secure random values.