Understand Global Namespace in Node.js

Share this video with your friends

Send Tweet

In this lesson, we introduce the node global namespace object and demonstrate how global variables in node may not behave the way you think they do. We also briefly discuss the global 'require' object and how it operates in the global namespace.

Jeff Nolan
Jeff Nolan
~ 8 years ago

If you declare a global var called globalFoo in file module1.js, then...

var modFoo = require('./module1.js');

var newFoo = require('./module2.js');

Will the global var globalFoo be global to newFoo as well?

Konekoya
Konekoya
~ 6 years ago

Nope, the variable globalFoo will only live in the module1.js not module2.js

~ 2 years ago

Just a note to viewers: 'create a simple node.js module' takes you to a different node course, just keep that in mind in case you go wandering around without realizing it.

Ildar Karimov
Ildar Karimov
~ 2 years ago

Clarify for me please. When we run 'global' in REPL it dosen't show globalFoo, but we can return globalFoo value running modFoo.returnFoo(). So, where that value exits, how is it soted, do we have two globals? When globalFoo.js runs? When it runs it has own globalFoo and stores it memory? Where can I find lesson about this?

Lucas Minter
Lucas Minter
~ 2 years ago

Hey Ildar, I've found an article that should hopefully get you the answers you're looking for: https://stackabuse.com/using-global-variables-in-node-js/