Lets say that I have an application:
./app.coffee:
express = require "express"
module.exports = app = express()
require "./models"
./models/index.coffee
app = require "../app"
Then I run the command: coffee app.coffee
The problem is that the code does not run the same way as when it is precompiled.
When I run my app with node (compiled):
app.coffee requires modelsmodels requires app and returns the module.exports (app)When I run my app with coffee:
app.coffee requires modelsmodels requires app but app run again and requires models againIt seems that module.exports is not working properly when running my app with coffee. Or maybe I'm doing something wrong?
Node has an altered behavior for managing module cycles which doesn't appear to be supported when using the coffee executable:
When there are circular
require()calls, a module might not be done being executed when it is returned.[...]
When
main.jsloadsa.js, thena.jsin turn loadsb.js. At that point,b.jstries to loada.js. In order to prevent an infinite loop an unfinished copy of thea.jsexports object is returned to theb.jsmodule.b.jsthen finishes loading, and its exports object is provided to thea.jsmodule.
If you can, try to avoid cycles. One possible alternative is:
express = require "express"
module.exports = app = express()
models = require "./models"
models app
module.exports = (app) ->
# ...