使用coffeescript的节点中的全局变量

coo*_*ool 2 node.js coffeescript express

我检查了这个如何在CoffeeScript中定义全局变量? 用于声明全局变量,即在app.js中声明并在routes/index.coffee中访问

我在app.coffee中声明了(导出?this).db = redis.createClient()并尝试使用db.set('online',Date.now(),(错误)访问routes.index.coffee中的数据库. ,回复) - > console.log(reply.toString()))这似乎不起作用......发生了什么..我在节点0.8.9

还有其他方法可以运行,但很想知道发生了什么......还尝试了app.coffee中的@db = redis.createClient(),它也不起作用

谢谢

Jon*_*ski 6

exports没有定义" 全局" ; 它定义了可用的模块的" 公共 "成员require.此外,exports始终是最初定义的exports === this,因此(exports ? this)实际上并没有做任何事情.

但是,由于全局变量通常不受欢迎(并且确实打败了Node模块系统的某些意图),因此Web应用程序的一种常见方法是定义一个自定义中间件,允许访问db作为reqres对象的属性:

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

这方面的例子中可以找到decorate.jsnpm-www,后面的仓库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)

  // ...
}
Run Code Online (Sandbox Code Playgroud)

但是,如果你仍然宁愿定义db为全局,Node.JS定义了一个global你可以附加到的变量:

global.db = redis.createClient()
Run Code Online (Sandbox Code Playgroud)