Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
737 views
in Technique[技术] by (71.8m points)

node.js - 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')
  @
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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: {}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...