Nodejs:如何导出多个对象?

时间:2013-11-21 14:00:43

标签: node.js coffeescript

我是Nodejs的新手。如何导出多个对象?例如

fs = require("fs")
Sequelize = require 'sequelize'

module.exports = (config)->
  sequelize = new Sequelize(
    config.database.name
    config.database.username
    config.database.password
    config.database.options
  )

  fs.readdirSync(config.root+'/server/models/').forEach (file)->
    module.exports['Page'] = sequelize.import(config.root + '/server/models/' + file) # --> export this model 
  sequelize # --> export this object

我想使用类似的Page模型:

Page = require('./models').Page

我想使用Sequelize对象:

Sequelize = require('./models').Sequelize

感谢您的建议:D

已更新: 解决了以下方式:

fs = require("fs")
Sequelize = require 'sequelize'

module.exports = (config)->
  @Sequelize = new Sequelize(
    config.database.name
    config.database.username
    config.database.password
    config.database.options
  )

  fs.readdirSync(config.root+'/server/models/').forEach (file)->
    @Page = sequelize.import(config.root + '/server/models/' + file)
  @

但我有另一个问题。如何动态分配模型?

已更新 解决了第二个问题:

fs = require("fs")
Sequelize = require 'sequelize'

module.exports = (config)->
  @Sequelize = new Sequelize(
    config.database.name
    config.database.username
    config.database.password
    config.database.options
  )

  # @Page = sequelize.import(config.root + '/server/models/page')
  fs.readdirSync(config.root+'/server/models/').forEach (file)->
    str = file.replace('.coffee', '')
    model = str.charAt(0).toUpperCase() + str.slice(1)
    @[model] = @Sequelize.import(config.root + '/server/models/' + file) if ~file.indexOf('.coffee')
  @

1 个答案:

答案 0 :(得分:5)

将它们包装在对象文字中。在纯JS(没有CoffeeScript)中将是:

module.exports = {
    Page: {}, // or whatever you want to assign it to
    Serialize: {} // again, set it to what you like
};

在coffeescript中你使用缩进,除非你想制作一个空对象:

module.exports =
  Page: {},
  Serialize: {}