我试图创建一个小应用程序来存储使用nodejs和mongodb的代码片段我正在使用Coffeescript编写应用程序。
问题是,我想在模块中分离代码所以我创建了这个文件夹结构
/app
/lib
/models
/routes
core.coffee
的核心。coffee是使用expressjs的"服务器"应用在这个文件中,我输入
mongoose = module.exports.mongoose = require 'mongoose'
app = module.exports.app = express.createServer()
Snippet = module.exports.Snippet = require __dirname+'/lib/models/Snippet'
#App configurations
routes = require(__dirname+'/lib/routes/general')
在lib/模型/片段mongoose = module.parent.exports.mongoose
Snippet = new mongoose.Schema
title:
type: String
default:'Title'
mongoose.model 'Snippet',Snippet
exports.Snippet = mongoose.model 'Snippet'
在/lib/routes/general.coffee app = module.parent.exports.app
mongoose = module.parent.exports.mongoose
Snippet = module.parent.exports.Snippet
app.get '/test', (req,res)->
snip = new Snippet()
res.send snip
但这不起作用,我得到以下错误信息
TypeError: object is not a function
at Object.CALL_NON_FUNCTION_AS_CONSTRUCTOR (native)
我怎么才能做到呢?
我看到一个值得注意的错别字:
Snippet = module.exports.Snippt = require __dirname+'/lib/models/Snippet'
将module.exports.Snippt
改为module.exports.Snippet
让我们从如何使用require开始。看起来您正在尝试将项目的所有需求加载到core中。咖啡,然后再出口到其他地方。这是一种奇怪的方式,大多数人只是在每个需要它们的模块中require
这些库(至少现在,请参阅我的答案的结尾)。
例如,你在lib/models/Snippet中需要mongoose,所以只需在那里要求它:
/lib/模型片段:
mongoose = require 'mongoose'
接下来,不需要使用__dirname
来要求一个相对路径,要求复制一个以./
开头的路径:
require './lib/models/Snippet'
我仍然不能让代码干净地工作(我猜我们没有看到完整的代码),但它可能足以让你走上正确的道路。
最后,如果你想导出主模块上的所有内容,我建议你看看dave-elkan的图层项目。普通版本不支持coffeescript,但我已经创建了一个支持的分支。
它非常轻量级,并且几乎不需要对项目结构做任何假设。基本思路是给layers()
一个express app对象和一个目录。Layers将扫描该目录,并将所有子目录设置为应用对象上的图层。
在你的情况下,你会传递一个rootPath: __dirname + '/lib'
和你的应用程序对象会得到app.models.Snippet
和app.routes.general
添加到它。这仍然不是我想要的结构,但是你可以从那里想出一些符合你风格的东西。