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)
Please see this answer explaining module.exports vs exports = foo vs exports.foo = bar
In short, if you assign a local variable named
exportsto a brand new object, you cannot assign properties to the “real”exportsobject, and thus your code doesn’t work as expected. You can either A) assign an object tomodule.exportsor B) assign properties to the existingexportsobject.One pattern that works nicely in CoffeeScript is this: