MyInternships.in

Node.js Basics

Node.js Global Objects

Node provides globals that do not exist in browsers: process for environment and lifecycle, __dirname and __filename for paths in CommonJS, Buffer for binary data, and console for output.


What is Global Objects in Node.js?

Node provides globals that do not exist in browsers: process for environment and lifecycle, __dirname and __filename for paths in CommonJS, Buffer for binary data, and console for output.

Global Objects example

The globals you will actually use
JavaScript
console.log(process.argv);        // command-line arguments
console.log(process.env.NODE_ENV); // environment variables
console.log(process.platform);     // 'linux' | 'darwin' | 'win32'
console.log(process.pid);

process.on('SIGINT', () => {
  console.log('Shutting down…');
  process.exit(0);
});

// CommonJS only
console.log(__dirname, __filename);

The ES module equivalent of __dirname

JavaScript
import { fileURLToPath } from 'node:url';
import { dirname } from 'node:path';

const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);

// Node 20.11+ offers a shorter form:
// import.meta.dirname

Key points to remember

  • process.env holds environment variables and is how configuration reaches the app.
  • __dirname and __filename are undefined in ES modules.
  • process.exit(0) means success; any non-zero code signals failure.
  • globalThis works in both Node and the browser.

Common mistakes with Global Objects

  • Using __dirname in an ES module and getting a ReferenceError.
  • Calling process.exit() before pending writes flush, truncating output.

Node.js Global Objects— Interview Questions & FAQs

Why is __dirname not defined in my Node file?+

The file is an ES module — either it ends in .mjs or package.json has "type": "module". Derive it from import.meta.url, or use import.meta.dirname on Node 20.11 and later.

Related Node.js Topics

Keep learning with these closely related lessons.

Ready to use your Node.js skills?

Find verified Node.js internships and fresher developer jobs across India.

Browse Node.js Internships