我正在尝试访问Express' app'变量在我的应用程序的一个子模块中。 一种方法是在调用子模块时将其作为参数传递,但我想避免使用它。 This solution提到它是可能的,但是每次我尝试它都会得到异常,说对象不是函数(下面的回溯)
server.coffee
express = require 'express'
# Application Config
config = require './lib/config/config'
app = express()
# Start server
server = app.listen config.port, ->
logger.info "Express server listening on port #{config.port} in #{app.get("env")} mode"
# load procesor
fooBarStreamProcessor = require('./lib/modules/fooBarStreamProcessor')
fooBarUpstream = new fooBarStreamProcessor(config.fooBar_host, config.fooBar_port)
# Expose app
exports = module.exports = app
fooBarStreamProcessor.coffee
events = require('events')
eventEmitter = new events.EventEmitter()
app = require("../../server")
console.log(app.get('something'))
module.exports = ->
return "I am some function"
回溯
TypeError: object is not a function
at Object.<anonymous> (~/devel/exampleproj/server.coffee:30:18)
at Object.<anonymous> (~/devel/exampleproj/server.coffee:1:1)
at Module._compile (module.js:456:26)
at Object.loadFile (~/devel/exampleproj/node_modules/coffee-script/lib/coffee-script/register.js:16:19)
at Module.load (~/devel/exampleproj/node_modules/coffee-script/lib/coffee-script/register.js:45:36)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (~/devel/exampleproj/lib/modules/fooBarStreamProcessor.coffee:9:7)
at Object.<anonymous> (~/devel/exampleproj/lib/modules/fooBarStreamProcessor.coffee:1:1)
at Module._compile (module.js:456:26)
at Object.loadFile (~/devel/exampleproj/node_modules/coffee-script/lib/coffee-script/register.js:16:19)
at Module.load (~/devel/exampleproj/node_modules/coffee-script/lib/coffee-script/register.js:45:36)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (~/devel/exampleproj/server.coffee:3:25)
at Object.<anonymous> (~/devel/exampleproj/server.coffee:1:1)
at Module._compile (module.js:456:26)
检查后,fooBarStreamProcessor
似乎设置为{}
,而不是fooBarStreamProcessor.coffee
所需的实际功能。
在进行问题排查时,我尝试在require("./server")
的第一行中添加server.coffee
之类的内容,但它排除了错误,但代码执行了两次。
任何想法我该如何解决这个问题?
答案 0 :(得分:0)
问题是,在包含子模块之后,此行将被执行:
# Expose app
exports = module.exports = app
尝试将其移至应用定义:
app = module.exports = express()
并确保在需要子模块之前在应用上设置任何所需内容。
答案 1 :(得分:0)
是的,你有一个循环依赖。通常这意味着在需要的时候而不是在文件的开头加载一个,但是在这样的情况下,您的示例代码中并不清楚。在fooBarStreamProcessor.coffee
中,您可能需要server
在您要导出的功能中。
events = require('events')
eventEmitter = new events.EventEmitter()
module.exports = ->
app = require("../../server")
console.log(app.get('something'))
return "I am some function"
答案 2 :(得分:0)
找到解决方案 - 导致问题的是Coffeescripts全局包装器。
使用'-b'
(裸)选项编译coffeescript会阻止这种情况发生。有趣的是,运行coffeescript(没有-c
标志)会导致出现相同的错误。