3 min read
•Question 7 of 62easyWhat are Global Objects in Node.js?
Understanding Node.js global objects and variables.
What You'll Learn
- Available global objects
- Difference from browser globals
- Common usage
Global Objects
Unlike browsers (where window is global), Node.js has different global objects:
code.jsJavaScript
// Process - info about current process
console.log(process.pid);
console.log(process.env.NODE_ENV);
console.log(process.cwd());
console.log(process.argv);
// Console
console.log('message');
console.error('error');
console.table([{a: 1}, {a: 2}]);
// Timers
setTimeout(() => {}, 1000);
setInterval(() => {}, 1000);
setImmediate(() => {});
// Buffer
const buf = Buffer.from('hello');
// Module-level (not truly global)
__dirname // current directory path
__filename // current file path
module // current module
exports // module.exports shortcut
require() // import modulesglobal Object
code.jsJavaScript
// Like window in browser
global.myVar = 'accessible everywhere';
// Check if global
console.log(global.setTimeout === setTimeout); // trueglobalThis (ES2020)
code.jsJavaScript
// Works in both Node.js and browser
globalThis.myVar = 'universal global';