var express = require('express'); var app = express(), What is express()?? is it a method or a constructor? Where does it come from

后端 未结 5 1941
南方客
南方客 2020-12-02 14:30
var express = require(\'express\'); 
var app = express();

This is how we create an express application. But what is this \'express()\'? Is it a met

5条回答
  •  自闭症患者
    2020-12-02 15:31

    Whenever you import a module like

    const express = require('express')
    

    express is a module with functions or objects or variables assigned to it . take a look at /lib/express

    you are able to access the function createApplication inside express module as express() because the function is assigned directly to the module like

    exports = module.exports = createApplication;

    function createApplication(){
        var app = function(req, res, next) {
        app.handle(req, res, next);
      };
    //other codes
    }
    

    so you are able to access the function createApplication just calling express() as function

    now when you check out the other section of the express library, you can see a bunch of other objects attached to the exports special object as well.

    /**
     * Expose the prototypes.
     */
    
    exports.application = proto;
    exports.request = req;
    exports.response = res;
    
    /**
     * Expose constructors.
     */
    
    exports.Route = Route;
    exports.Router = Router;
    
     // other exports
    

    these objects or function assigned to export special object can be accessed from the import section using express as an object.

    express.{name}

    express.Route
    express.Router etc
    

    In the end you are just exporting a bunch of methods or objects that are attached to the module.export special object inside express js file

    to read more on module.export special object go here

提交回复
热议问题