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.
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:
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:
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
Conclusion
These global objects are used in almost every Node.js application.
Your Hero to Zero Node.js journey is getting deeper 💚🚀