Global variables in NodeJS

I should start by saying this: You should probably never, ever do this. If you do want to do this, the config example I’m about to give is about the only valid use case that I can think of. Now that’s out of the way, let’s take a look at the problem (and the solution!).

Imagine that we have two files, index.js (our entry point into the app) and hello.js, a module that we’re using. hello.js looks like this:

module.exports = function(name){
    return config.salutation + " " + name;
}

All it does, it takes a name and returns a salutation, then the name that was passed in. We call this from index.js like so:

var hello = require("./hello");
console.log(hello("Michael"));

hello.js is trying to read salutation out of our config. We haven’t defined config yet, so let’s do that.

var hello = require("./hello");
var config = {"salutation": "Hello"};
console.log(hello("Michael"));

Next we run index.js, but unfortunately it doesn’t work.

$ node index.js                                                                                                    

/home/michael/global-config/hello.js:2
    return config.salutation + " " + name;
               ^
ReferenceError: config is not defined

This is because of how variable scope works in NodeJS. Each module has it’s own scope by default. To force something into the global scope, you use the global keyword. Let’s change index.js to use global.

var hello = require("./hello");
global.config = {"salutation": "Hello"};
console.log(hello("Michael"));

Now, our module works:

$ node index.js                                                                                                    
Hello Michael

As I mentioned, this should only really be used when you have no other choice (legacy codebase etc). If at all possible, passing your config as a parameter to your modules is a much better way to do it.

Michael is a polyglot software engineer, committed to reducing complexity in systems and making them more predictable. Working with a variety of languages and tools, he shares his technical expertise to audiences all around the world at user groups and conferences. You can follow @mheap on Twitter

Thoughts on this post

Leave a comment?

Leave a Reply