5. Node.js Global Objects – __dirname, __filename, process & Buffer

Node.js provides powerful global objects that can be used directly without importing any module. These objects help us interact with the system, files, and memory.

Node.js global objects overview

Important global objects in Node.js (__dirname, process, Buffer)

1. What are Global Objects?

Global objects are available everywhere in your Node.js application. You don’t need to import them using require().

2. __dirname

Returns the directory name of the current file.

console.log(__dirname);

Output:

C:\Users\YourFolder\node-project

Used for handling file paths.

3. __filename

Returns the full path of the current file.

console.log(__filename);

4. process Object

The process object provides information about the current Node.js process.

Check Node Version

console.log(process.version);

Current Working Directory

console.log(process.cwd());

Environment Variables

console.log(process.env);

5. Buffer

Buffer is used to handle binary data in Node.js.

  • Reading files
  • Handling streams
  • Working with TCP servers

Example:

const buf = Buffer.from("Hello");

console.log(buf);
console.log(buf.toString());

Output:

<Buffer 48 65 6c 6c 6f>
Hello

6. Real-World Usage

  • Creating dynamic file paths
  • Accessing environment variables
  • Handling file uploads
  • Working with streams

7. Common Beginner Mistakes

  • Trying to import global objects
  • Using __dirname in browser
  • Not converting Buffer to string
Global objects are available only in Node.js, not in the browser.

Conclusion

These global objects are used in almost every Node.js application.

Your Hero to Zero Node.js journey is getting deeper 💚🚀

Chakrapani U

Hi, I’m Chakrapani Upadhyaya, an IT professional with 15+ years of industry experience. Over the years, I have worked on web development, enterprise applications, database systems, and cloud-based solutions. Through this blog, I aim to simplify complex technical concepts and help learners grow from beginners to confident, industry-ready developers.

Previous Post Next Post

نموذج الاتصال