Jean-Philippe Leclerc
Jean-Philippe Leclerc

Reputation: 6805

module.exports not caching when using coffeescript to run my node.js application

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):

When I run my app with coffee:

It seems that module.exports is not working properly when running my app with coffee. Or maybe I'm doing something wrong?

Upvotes: 3

Views: 171

Answers (1)

Jonathan Lonowski
Jonathan Lonowski

Reputation: 123503

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.js loads a.js, then a.js in turn loads b.js. At that point, b.js tries to load a.js. In order to prevent an infinite loop an unfinished copy of the a.js exports object is returned to the b.js module. b.js then finishes loading, and its exports object is provided to the a.js module.

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) ->
  # ...

Upvotes: 1

Related Questions