【发布时间】:2026-01-14 09:35:01
【问题描述】:
我正在尝试在我的应用程序的一个子模块中访问 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 所需的实际功能。
在进行故障排除时,我尝试在server.coffee 的第一行中包含类似require("./server") 的内容,它消除了错误,但代码被执行了两次。
有什么办法可以解决这个问题吗?
【问题讨论】:
标签: node.js express coffeescript