Correct way of exporting module

This question already has an answer here:

  • What is the purpose of Node.js module.exports and how do you use it? 10 answers

  • Both methods of using module.exports or module.exports.FUNCTION_NAME are okay but the difference comes when you require these functions.

    Let me show the difference using an Example.

    a. Assigning function directly to module.exports

    // mkdir.js
    module.exports = function(){
           console.log("make directory function");
    };
    
    // app.js
    var mkdir = require("mkdir.js");
    mkdir(); // prints make directory function
    

    b. Exporting function at property in module.exports

    // mkdir.js
    module.exports.first = function(){
                         console.log('make directory function');
    };
    
    // app.js
    var mkdir = require('mkdir.js');
    mkdir.mkdir(); // make directory function
    

    Hope it helps!


    module.exports = makeDir;

    is the correct method if you are exporting only one object from javascript file.

    IN CASE YOU NEED TO EXPORT MORE THAN ONE OBJECTS

    var makeDir = {
     obj1 : function(){},
     obj2 : function(){}
    }
    module.exports = makeDir;
    

    This way you can use makeDir.obj1 and makeDir.obj2 in other file.

    链接地址: http://www.djcxy.com/p/96622.html

    上一篇: JavaScript对象混淆

    下一篇: 正确的出口模块方式