Search code examples
javascriptnode.jsv8

Multiple module.exports in a node js file


How does the Nodejs engine decides when a file has multiple module.exports and it is being required by another file ? How does the final closure is being calculated ?


Solution

  • It uses the value that module.exports has when the execution of the module has finished:

    module.exports = { foo: 'bar' };
    module.exports = { a: 17.8 };    // overwrite "module.exports"
    module.exports = 5;              // and again 
    module.exports = { b: 123 };     // and again
    

    Now, when you require the module, you will get { b: 123 }.

    module.exports is not a magic keyword, it's just a variable that you can set to tell NodeJS what should be exported.