What do “module.exports” and “exports.methods” mean in NodeJS / Express?

前端 未结 5 477
谎友^
谎友^ 2020-12-02 05:24

Looking at a random source file of the express framework for NodeJS, there are two lines of the code that I do not understand (these lines of code

5条回答
  •  既然无缘
    2020-12-02 06:00

    To be more specific:

    module is the global scope variable inside a file.

    So if you call require("foo") then :

    // foo.js
    console.log(this === module); // true
    

    It acts in the same way that window acts in the browser.

    There is also another global object called global which you can write and read from in any file you want, but that involves mutating global scope and this is EVIL

    exports is a variable that lives on module.exports. It's basically what you export when a file is required.

    // foo.js
    module.exports = 42;
    
    // main.js
    console.log(require("foo") === 42); // true
    

    There is a minor problem with exports on it's own. The _global scope context+ and module are not the same. (In the browser the global scope context and window are the same).

    // foo.js
    var exports = {}; // creates a new local variable called exports, and conflicts with
    
    // living on module.exports
    exports = {}; // does the same as above
    module.exports = {}; // just works because its the "correct" exports
    
    // bar.js
    exports.foo = 42; // this does not create a new exports variable so it just works
    

    Read more about exports

提交回复
热议问题