Node.js中的模块接口module.exports浅析

    xiaoxiao2021-12-14  15

    在写node.js代码时,我们经常需要自己写模块(module)。

    同时还需要在模块最后写好模块接口,声明这个模块对外暴露什么内容。

    实际上,node.js的模块接口有多种不同写法。

    这里作者对此做了个简单的总结。  

    返回一个JSON Object 如下代码是一个简单的示例。 

     var exp = {

    "version": "1.0.0",

    "function1": null,

    "module1": null,

    };

    module.exports = exp; 

     这种方式可以用于返回一些全局共享的常量或者变量,

    例如  

     // MATH.js

    var MATH = {

    "pi": 3.14

    "e": 2.72,

    };

    module.exports = MATH;  

    调用方式为 

    var MATH = require("./MATH")

    console.log(MATH.pi);

     这种方式还可以用于返回几个require的其他模块,可以实现一次require多个模块 

    // module_collection.js

    var module_collection = {

      "module1": require("./module1"),

    "module2": require("./module2"),

    };

    module.exports = module_collection;

    调用方式为

    var module_collection = require("./module_collection");

    var module1 = module_collection.module1;

    var module2 = module_collection.module2;

    // Do something with module1 and module2 

    其实这种方式还有个变种,如下,通常可以返回几个函数 

    // functions.js

    var func1 = function() {

      console.log("func1");

    };

    var func2 = function() {

      console.log("func2");

    };

    exports.function1 = func1;

    exports.function2 = func2;

    调用方式为

    var functions = require("./functions");

    functions.function1();

    functions.function2();  返回一个构造函数,也就是一个类 如下是一个简单的示例。  

    // CLASS.js

    var CLASS = function(args) {

      this.args = args;

    }

    CLASS.prototype.func = function() {

      console.log("CLASS.func");

      console.log(this.args);

    };

    module.exports = CLASS;  

    调用方法为

    var CLASS = require("./CLASS")

    var c = new CLASS("arguments"); 

    返回一个普通函数 如下是一个简单的示例 复制代码

    // func.js

    var func = function() {

    console.log("this is a testing function");

    };

    module.exports = func;  

    调用方法为

    var func = require("./func");

    func(); 

    返回一个对象object 如下是一个简单的示例  

    // CLASS.js

    var CLASS = function() {

      this.say_hello = "hello";

    };

    CLASS.prototype.func = function() {

      console.log("I say " + this.say_hello);

    };

    module.exports = new CLASS();  

    调用方法为

    var obj = require("./CLASS");

    obj.func();  

    有时候我们需要模块返回一个单例 singleton. 可以利用上面的方式1和方式4来实现。也就是如下两种形式

    // MATH.js

    var MATH = {

    "pi": 3.14,

    "e": 2.72,5 };

    module.exports = MATH;

    以及  

    // CLASS.js

    var CLASS = function() {

      this.say_hello = "hello";

    };

    CLASS.prototype.func = function() {

    console.log("I say " + this.say_hello);

    };

    module.exports = new CLASS();

    转载请注明原文地址: https://ju.6miu.com/read-964470.html

    最新回复(0)