Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Nodejs: How to export multiple objects?

I'm new to Nodejs. How to export multiple objects? For example

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

I want to use Page model something like:

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

I want to use Sequelize object something like:

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

Thank you for advice :D

UPDATED: Solved following way:

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)
  @

but I have an another problem. How to assign models dynamically?

UPDATED Solved second problem following way:

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')
  @
like image 536
Zeck Avatar asked Nov 21 '13 14:11

Zeck


1 Answers

Just wrap them in an object literal. In pure JS (without CoffeeScript) that would be:

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

In coffeescript you use indents, except when you want to make an empty object:

module.exports =
  Page: {},
  Serialize: {}
like image 86
Slavo Avatar answered Oct 15 '22 02:10

Slavo