1

I find that

exports.index = (req, res) ->
  res.render "index",
    title: "Hello"

compiles to

exports.index = function(req, res) {
    return res.render("index", { title: "Hello" })
}

Something that works with ExpressJS. However, I thought that I could use:

exports = 
    index: (req, res) ->
        res.render "index",
            title: "Hello"

so that I wont have to type exports.xxx for all routes, but that compiles to

var exports;
exports = {
  index: function(req, res) {
    return res.render("index", {
      title: "Hello"
    });
  }
};

which doesn't appear to work with ExpressJS, why?

Error: In /labs/Projects/jiewmeng/routes/index.coffee, Parse error on line 1: Unexpected '{'
    at Object.parseError (/usr/lib/node_modules/coffee-script/lib/coffee-script/parser.js:477:11)
    at Object.parse (/usr/lib/node_modules/coffee-script/lib/coffee-script/parser.js:554:22)
    at /usr/lib/node_modules/coffee-script/lib/coffee-script/coffee-script.js:43:20
    at Object..coffee (/usr/lib/node_modules/coffee-script/lib/coffee-script/coffee-script.js:19:17)
    at Module.load (module.js:353:31)
    at Function._load (module.js:311:12)
    at Module.require (module.js:359:17)
    at require (module.js:375:17)
    at Object.<anonymous> (/labs/Projects/jiewmeng/server.coffee:6:12)
    at Object.<anonymous> (/labs/Projects/jiewmeng/server.coffee:74:4)
Jiew Meng
  • 84,767
  • 185
  • 495
  • 805
  • possible duplicate of [Understanding exports in NodeJS](http://stackoverflow.com/questions/9627044/understanding-exports-in-nodejs) – Trevor Burnham Jun 23 '12 at 02:23

1 Answers1

4

Please see this answer explaining module.exports vs exports = foo vs exports.foo = bar

In short, if you assign a local variable named exports to a brand new object, you cannot assign properties to the "real" exports object, and thus your code doesn't work as expected. You can either A) assign an object to module.exports or B) assign properties to the existing exports object.

One pattern that works nicely in CoffeeScript is this:

module.exports = {
  SomeClass
  someFunction
  someObject
}
Community
  • 1
  • 1
Peter Lyons
  • 142,938
  • 30
  • 279
  • 274
  • So can I say my method overrides all existing exports? Then if I use module.exports, it will "extend" the existing exports variable? – Jiew Meng Jun 23 '12 at 10:31
  • 1
    No, if you do `exports.property = foo` you "extend" the exports object. Doing `exports = bar` is a mistake/bug and won't have any effect on the properties exported by your module. Doing `module.exports = foo` lets you export a brand new object as opposed to the empty object node.js provides for you. – Peter Lyons Jun 23 '12 at 14:01