Welcome to the Linux Foundation Forum!

module exports question

A. module.exports = func
C. module.exports = {func}

Can someone point me to more detailed reading on why the answer is A and C is incorrect above: when a given a function named func, how can func be exposed such that when the file that func is in is loaded by another module, the result of the require statement is func?

Comments

  • hey @sood

    this is how the CJS (require/module.exports) module system works.

    When your file is loaded by Node it wraps the contents of the file in a function like this

    (function (require, module, exports, __filename, __dirname) {
    
    })(...argsPreparedByNodeToBePassedToYourModule)
    

    This creates a function scope that those items are injected into

    When you call require and reference a file, a module object (it's just a plain object) is injected into that wrapper function as it's called. After the wrapper function is called, the require function returns whatever the value of module.exports is.

    e.g. given the code:

      module.exports = function thisIsFineToDo () { return 'hooray' }
    

    It will be wrapped like so:

    (function (require, module, exports, __filename, __dirname) {
      module.exports = function thisIsFineToDo () { return 'hooray' }
    })(...argsPreparedByNodeToBePassedToYourModule)
    

    And the require function will call that and return module.exports, i.e. the thisIsFineToDo function.

    It's also important to note, functions are first class citizens in JS - they're just values like anything else.

    Hope that helps.

Categories

Upcoming Training