I asked here: node.js require inheritance?
and was told that I can set variables to the global scope by leaving out the var.
This does not work for me.
ie:
_ = require('underscore');
Does not make the _ available on required files. I can set with express's app.set
and have it available elsewhere though.
Can somebody confirm that this is supposed to work? Thanks.
In node, you can set global variables via the "global" or "GLOBAL" object:
or more usefully...
From the node source, you can see that these are aliased to each other:
In the code above, "this" is the global context. With the commonJS module system (which node uses), the "this" object inside of a module (ie, "your code") is NOT the global context. For proof of this, see below where I spew the "this" object and then the giant "GLOBAL" object.
** Note: regarding setting "GLOBAL._", in general you should just do
var _ = require('underscore');
. Yes, you do that in every single file that uses underscore, just like how in Java you doimport com.foo.bar;
. This makes it easier to figure out what your code is doing because the linkages between files are 'explicit'. Mildly annoying, but a good thing. .... That's the preaching.There is an exception to every rule. I have had precisely exactly ONE instance where I needed to set "GLOBAL._". I was creating a system for defining "config" files which were basically JSON, but were "written in JS" to allow a bit more flexibility. Such config files had no 'require' statements, but I wanted them to have access to underscore (the ENTIRE system was predicated on underscore and underscore templates), so before evaluating the "config", I would set "GLOBAL._". So yeah, for every rule, there's an exception somewhere. But you had better have a darn good reason and not just "i get tired of typing 'require' so I want to break with convention".