Search code examples
node.jsmorgan

morgan.format is not a function when I study the logger middleware


Hi I am learning the source code about morgan

when I saw the line morgan.format('combined', ...) for my understand, why it can run success and not cause morgan.format is not a function. when I extract the main code run in my local and I got the error. how this place is implemented?

can anybody tell me ? thanks in advance.


Solution

  • Thanks to the module.exports magic that makes the format() method accessible to the main morgan() function.

    Here is a minimal reproduction:

    module.exports = morgan
    module.exports.format = format  // format() method is now available to morgan
    
    function morgan() {}
    
    morgan.format()  // Hello from format()
    
    function format() {
      console.log('Hello from format()')
    }
    

    In short, module.exports.some_method = some_method add the some_method() function to the main module.