Nodejs:如何导出多个对象? [英] Nodejs: How to export multiple objects?

查看:3424
本文介绍了Nodejs:如何导出多个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我要使用模型类似:

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

我想使用 Sequelize 对象:

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


b $ b

感谢您的建议:D

Thank you for advice :D

UPDATED
解决方法如下:

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
解决第二个问题如下:

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


推荐答案

只需将它们包装在对象字面量中。在纯JS(没有CoffeeScript)中:

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
};

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

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

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

这篇关于Nodejs:如何导出多个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆