agyanadda@gmail.com

Node.js Global Objects and process

Node.js Basics 1 min read Updated Dec 3, 2026 Topic 5 of 30

Global objects are available in every Node.js file without importing.

Common globals

  • console — log, error, table, time / timeEnd
  • setTimeout, setInterval, setImmediate
  • globalThis — the global object (like window in browsers)
  • fetch, URL, Buffer, structuredClone

The process object

  • process.argv — command-line arguments (an array)
  • process.env — environment variables (process.env.PORT)
  • process.cwd() — the folder you ran the command from
  • process.exit(1) — stop the program (non-zero = error)
  • process.platform — win32, linux, darwin
  • process.memoryUsage()

File location

  • In CommonJS: __dirname (folder of the current file) and __filename
  • In ES modules: import.meta.dirname and import.meta.filename (newer Node versions), or import.meta.url

Use these to build paths relative to your file, not to where the command was run.

Example

Example — A tiny command-line greeter JavaScript
// greet.js  (run: node greet.js Asha 3)
const [, , name = 'friend', times = '1'] = process.argv;

for (let i = 0; i < Number(times); i++) {
  console.log(`Hello, ${name}!`);
}

console.log('Running on:', process.platform);
console.log('Port from env:', process.env.PORT ?? 'not set');

if (!process.argv[2]) {
  console.error('Tip: pass your name, e.g. node greet.js Asha');
  process.exit(1);
}

node greet.js Asha 3 prints "Hello, Asha!" three times, then the platform and port. process.argv[0] is node and [1] is the script path, so user arguments start at index 2.

Test Yourself With Exercises

Exercise 1 Multiple Choice

Which property holds environment variables?

Exercise 2 True / False

process.argv[2] is the first argument you type after the script name.

Exercise 3 Fill in the Blank

In CommonJS, the folder of the current file is ___

Frequently Asked Questions

__dirname exists only in CommonJS. In ES modules use import.meta.dirname (newer Node versions) or path.dirname(fileURLToPath(import.meta.url)).