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

前端 未结 5 470
谎友^
谎友^ 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:05

    To expand on Raynos's answer...

    exports is basically an alias for module.exports - I recommend just not using it. You can expose methods and properties from a module by setting them on module.exports, as follows:

    //file 'module1.js'
    module.exports.foo = function () { return 'bar' }
    module.exports.baz = 5
    

    Then you get access to it in your code:

    var module1 = require('module1')
    console.log(module1.foo())
    console.log(module1.baz)
    

    You can also override module.exports entirely to simply provide a single object upon require:

    //glorp.js
    module.exports = function () {
      this.foo = function () { return 'bar' }
      this.baz = 5
      return this // need to return `this` object here
    }
    

    Now you've got a nice prototype:

    var g1 = new require('glorp')()
    console.log(g1.foo())
    console.log(g1.baz)
    

    There are myriad other ways to play with module.exports and require. Just remember, require('foo') always returns the same instance even if you call it multiple times.

    Note

    For the following to work,

    var g1 = new require('glorp')()
    console.log(g1.foo())
    console.log(g1.baz) 
    

    this has to be returned in the function that is assigned to module.exports. Otherwise, you'll get a TypeError:

    console.log(g1.foo())
              ^
    TypeError: Cannot read property 'foo' of undefined
    

提交回复
热议问题