简体   繁体   中英

When exporting a module like this, what happens?

I was looking up some database connection Google searches when I saw something that exported an instance of a module as such

const foo = () => {
// Do stuff
};
...

module.exports = foo();

I don't know what this is called but how does nodejs treat exporting a function invocation vs an object or the function itself (without calling it)?

Thank you

The foo function only gets called once no matter how many times you require the module.

This is very simplified explanation of what is happening behind the scenes in Node.js

// cache for modules
var modules = {};

// very simplified require function
function require(name) {

    // check cache
    if (modules[name])
        // so if it has already been required it returns the cached result
        return modules[name].module.exports;

    // it will resolve path to the required module
    // and loads the file content
    // not showing here

    var obj = { module: { exports: {}}};
    
    // node will wrap the code in a function similar to bellow
    function module(module, exports){
    
        const foo = () => {
        // Do stuff
        };
        ...
        
        module.exports = foo();
    
    };
    
    module(obj.module, obj.module.exports);
    
    // and now cache it
    modules[name] = obj;

   return obj.module.exports;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM