【问题标题】:Node.js: Call code from other filesNode.js:从其他文件调用代码
【发布时间】:2011-11-13 16:18:36
【问题描述】:

我的主文件中有很多架构要删除到另一个文件中。

我该怎么做?

例如:

EntrySchema = new Schema 
    aa : String
    record : String
    status : String

CreditSchema = new Schema 
    credit : Number
    minute : Number
    date : Date
    #belongs_to subdomain

【问题讨论】:

    标签: javascript node.js coffeescript


    【解决方案1】:

    使用预定义的exports 对象。以下适用于.coffee.js 文件:

    将以下内容发送至schemas.coffee

    exports.EntrySchema = new Schema 
        aa : String
        record : String
        status : String
    
    exports.CreditSchema = new Schema 
        credit : Number
        minute : Number
        date : Date
        #belongs_to subdomain
    

    然后在 main.js 中你可以这样做:

    var s = require('./schemas')
    var foo = s.CreditSchema
    

    s 成为 ID 为 ./schemas 的模块的 exports 对象。 ./schemas.coffee 也可以,但不建议这样做,因为稍后您可以将 schemas.coffee 重构为 schemas.jsschemas/ 子文件夹甚至是用 C++ 实现的 DLL。

    一种常见的做法是对模块名称和对导出对象的引用使用相同的名称:

    var schemas = require('./schemas')
    

    另一种常见做法是在每次导出时同时使用fooexports.foo

    EntrySchema = exports.EntrySchema = new Schema 
        aa : String
        record : String
        status : String
    
    CreditSchema = exports.CreditSchema = new Schema 
        credit : Number
        minute : Number
        date : Date
        #belongs_to subdomain
    

    因此您仍然可以在schemas.coffee 中使用较短的EntrySchema 名称,而不必在schemas.coffee 中的任何地方都使用exports.EntrySchema

    这两种做法都很方便,但既不强制也不强制。

    这个exports 工具是CommonJS Modules 规范的一个实现。标准见http://www.commonjs.org/specs/modules/1.0/,Node.JS中具体实现见http://nodejs.org/docs/latest/api/modules.html

    【讨论】:

    • 它工作正常,直到有这样的嵌入式文档:exports.AccountSchema = new Schema phone : String users : [UserSchema] custphones : [CustphoneSchema] credit : Number
    • 返回:ReferenceError: UserSchema is not defined
    • 修改了答案。另一种解决方案是仅导出顶级架构。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多