Node.js Process

The process object is a global available in every Node.js file without importing. It contains information about the current process and lets you control it.

process.env

process.env is an object containing all environment variables. Use it to access secrets and configuration values without hardcoding them.

console.log(process.env.NODE_ENV);  // 'development' or 'production'
console.log(process.env.PORT);      // '3000' or whatever you set

// Fall back to a default if the variable is not set
const port = process.env.PORT || 3000;

process.env values are always strings. Convert to a number with Number() or parseInt() if needed.

See the Environment Variables page for how to load .env files with the dotenv package.

process.argv

process.argv is an array of command-line arguments. The first two elements are always the path to the Node executable and the path to your script.

// Run: node script.js hello world
console.log(process.argv);
// ['/path/to/node', '/path/to/script.js', 'hello', 'world']

const args = process.argv.slice(2); // ['hello', 'world']
console.log(args[0]); // 'hello'

process.exit()

process.exit() stops the process immediately. Use exit code 0 for success and any non-zero number for an error.

if (!process.env.API_KEY) {
  console.error('Missing API_KEY environment variable');
  process.exit(1);
}

process.memoryUsage()

Returns the memory usage of the current process in bytes:

console.log(process.memoryUsage());
// { rss: 22790144, heapTotal: 6037504, heapUsed: 3818032, external: 1583000 }

process.cwd()

Returns the current working directory, which is the directory from which you ran the node command:

console.log(process.cwd()); // /Users/you/my-project

See the Node.js Process documentation for all properties and methods.