一尘不染

Nodejs:如何导出多个对象?

node.js

我是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')
  @

阅读 624

收藏
2020-07-07

共1个答案

一尘不染

只需将它们包装在对象文字中即可。在纯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: {}
2020-07-07