Course contentsShow
← JavaScript
Lesson 1500 of 2,72333. JavaScript in Node.jsFree lesson

Process.exit() and Exit Codes

Terminating the Node.js process programmatically with success or error codes.

Process.exit() and Exit Codes

You'll learn how to programmatically terminate a Node.js process and signal success or failure to the operating system.

What is Process.exit()?

In Node.js, process.exit() immediately stops your program's execution. Think of it like an emergency stop button—when called, Node.js halts everything, skips any remaining code, and returns control to the operating system.

Exit Codes: Signaling Success or Failure

When a program exits, it sends a numeric exit code back to the operating system or parent process. By convention:

  • 0 means "everything went fine" (success)
  • Non-zero (typically 1) means "something went wrong" (error)

This matters when scripts call other scripts, or when automation tools check if a process completed successfully.

Basic Usage

// Exit successfully
process.exit(0);

// Exit with an error
process.exit(1);

// Exit without specifying (defaults to 0)
process.exit();

Real-World Example

const requiredVar = process.env.API_KEY;

if (!requiredVar) {
  console.error('Error: API_KEY environment variable is required');
  process.exit(1); // Signal failure
}

console.log('Starting application...');
// Continue normal execution

When to Use It

Use process.exit() sparingly—it's abrupt and doesn't allow cleanup (like closing database connections). However, it's useful for:

  • Command-line tools that need to signal errors
  • Validation scripts that check prerequisites
  • Situations requiring immediate termination

Key Takeaway: process.exit(code) terminates your Node.js program immediately, with exit code 0 indicating success and non-zero values signaling errors to the operating system.