简体   繁体   English

使用coffeescript运行我的node.js应用程序时,module.exports不缓存

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

Lets say that I have an application: 让我们说我有一个应用程序:

./app.coffee: ./app.coffee:

express = require "express"
module.exports = app = express()
require "./models"

./models/index.coffee ./models/index.coffee

app = require "../app"

Then I run the command: coffee app.coffee 然后我运行命令: 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): 当我用node (已编译)运行我的应用程序时:

  • The app.coffee requires models app.coffee需要models
  • models requires app and returns the module.exports (app) models需要app并返回module.exports (app)

When I run my app with coffee : 当我用coffee运行我的应用程序时:

  • The app.coffee requires models app.coffee需要models
  • models requires app but app run again and requires models again models需要app但应用程序再次运行,并再次需要模

It seems that module.exports is not working properly when running my app with coffee . 使用coffee运行我的应用程序时,似乎module.exports无法正常工作。 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: 节点具有改变的行为,用于管理模块周期 ,使用coffee可执行文件时似乎不支持:

When there are circular require() calls, a module might not be done being executed when it is returned. 当存在循环的require()调用时,返回时可能无法执行模块。

[...] [...]

When main.js loads a.js , then a.js in turn loads b.js . main.js加载a.jsa.js依次加载b.js At that point, b.js tries to load a.js . 此时, b.js尝试加载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. 为了防止无限循环,将a.js导出对象的未完成副本返回给b.js模块。 b.js then finishes loading, and its exports object is provided to the a.js module. 然后b.js完成加载,并将其exports对象提供给a.js模块。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM