2

I checked this How do I define global variables in CoffeeScript? for declaring a global variable i.e., declaring in the app.js and accessing in the routes/index.coffee

I declared (exports ? this).db = redis.createClient() in the app.coffee and tried to access the db in the routes.index.coffee using db.set('online',Date.now(), (err,reply) -> console.log(reply.toString()) ) this doesn't seem to work...what is happening..I am on node 0.8.9

There are other approaches in which it works but curious to know what is happening... Also tried the @db = redis.createClient() in the app.coffee which doesn't work either

Thanks

Community
  • 1
  • 1
coool
  • 8,085
  • 12
  • 60
  • 80

1 Answers1

6

exports doesn't define "globals;" it defines "public" members of a module available via require. Also, exports is always initially defined and exports === this, so (exports ? this) isn't actually doing anything.

However, since globals are generally frowned upon (and do defeat some of the intents of Node's module system), a common approach for web applications is to define a custom middleware allowing access to the db as a property of the req or res objects:

# app.coffee
app.use (req, res, next) ->
  req.db = redis.createClient()
  next()
# routes/index.coffee
exports.index = (req, res) ->
  req.db.set('online', Date.now(), (err,reply) -> console.log(reply))

An example of this can be found in decorate.js of npm-www, the repository behind npmjs.org:

function decorate (req, res, config) {
  //...

  req.model = res.model = new MC

  // ...

  req.cookies = res.cookies = new Cookies(req, res, config.keys)
  req.session = res.session = new RedSess(req, res)

  // ...

  req.couch = CouchLogin(config.registryCouch).decorate(req, res)

  // ...
}

Though, if you'd still rather define db as a global instead, Node.JS defines a global variable you can attach to:

global.db = redis.createClient()
Jonathan Lonowski
  • 121,453
  • 34
  • 200
  • 199
  • thanks. I knew about the global object. But I was trying to understand why it was n't working when it seemed that it was working for everybody. – coool Sep 17 '12 at 20:28