I'm trying to declare global variables for my applications that I'm writing using Node.js and CoffeeScript. So I'm declaring it in a common file that is concatenated to both applications after compilation. In that file I have for example:
root = exports ? this
root.myVariable = 300
So my first application is a HTML one. When I try to access this variable, for example by
console.log myVariable
There is no problem with it. But my other application is a server application lauched by node command and I cannot access that variable in that application. I tried:
console.log root.myVariable
console.log myVariable
With first line I'm getting 'undefined' printed (so it looks that root is defined) and with the second one, I'm getting ReferenceError - myVariable is undefined.
So how can I access this variable?
Here is an output code in Javascript that I get, I guess it might be helpful:
(function() {
var root, _ref;
root = (_ref = typeof module !== "undefined" && module !== null ? module.exports : void 0) != null ? _ref : this;
root.myVariable = 300;
}).call(this);
(function() {
console.log(root.myVariable);
console.log(myVariable);
}).call(this);
You're close, but you need to change things just a little bit
# config.coffee
module.exports =
foo: "bar"
hello: "world"
db:
user: alice
pass: password1
# lib/a.coffee
config = require "../config"
# lib/b.coffee
config = require "../config"
# lib/db.coffee
dbconfig = require("../config").db