module.exports vs exports in Node.js

前端 未结 23 1844
自闭症患者
自闭症患者 2020-11-22 06:11

I\'ve found the following contract in a Node.js module:

module.exports = exports = nano = function database_module(cfg) {...}

I wonder what

23条回答
  •  借酒劲吻你
    2020-11-22 07:12

    in node js module.js file is use to run the module.load system.every time when node execute a file it wrap your js file content as follow

    '(function (exports, require, module, __filename, __dirname) {',+
         //your js file content
     '\n});'
    

    because of this wrapping inside ur js source code you can access exports,require,module,etc.. this approach is used because there is no other way to get functionalities wrote in on js file to another.

    then node execute this wrapped function using c++. at that moment exports object that passed into this function will be filled.

    you can see inside this function parameters exports and module. actually exports is a public member of module constructor function.

    look at following code

    copy this code into b.js

    console.log("module is "+Object.prototype.toString.call(module));
    console.log("object.keys "+Object.keys(module));
    console.log(module.exports);
    console.log(exports === module.exports);
    console.log("exports is "+Object.prototype.toString.call(exports));
    console.log('----------------------------------------------');
    var foo = require('a.js');
    console.log("object.keys of foo: "+Object.keys(foo));
    console.log('name is '+ foo);
    foo();
    

    copy this code to a.js

    exports.name = 'hello';
    module.exports.name = 'hi';
    module.exports.age = 23;
    module.exports = function(){console.log('function to module exports')};
    //exports = function(){console.log('function to export');}
    

    now run using node

    this is the output

    module is [object Object]
    object.keys id,exports,parent,filename,loaded,children,paths
    {}
    true
    

    exports is [object Object]

    object.keys of foo: name is function (){console.log('function to module exports')} function to module exports

    now remove the commented line in a.js and comment the line above that line and remove the last line of b.js and run.

    in javascript world you cannot reassign object that passed as parameter but you can change function's public member when object of that function set as a parameter to another function

    do remember

    use module.exports on and only if you wants to get a function when you use require keyword . in above example we var foo = require(a.js); you can see we can call foo as a function;

    this is how node documentation explain it "The exports object is created by the Module system. Sometimes this is not acceptable, many want their module to be an instance of some class. To do this assign the desired export object to module.exports."

提交回复
热议问题