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")

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" }

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

$ node index.js

    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" }

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.

November 18, 2013