2013-11-21 54 views
6

我是新來的Nodejs。如何導出多個對象?例如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') 
    @ 

回答

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

'='應該是':'在對象字面:) – robertklep

+1

當然。謝謝,@robertklep – Slavo

+0

謝謝你的回覆。查看我的更新:D – Zeck