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

1 Answer 1

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()
Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.