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

后端 未结 5 1927
南方客
南方客 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:25

    You’ll use Node’s require function to use the express module. require is similar to keywords like import or include in other languages. require takes the name of a package as a string argument and returns a package. There’s nothing special about the object that’s returned—it’s often an object, but it could be a function or a string or a number.

    var express = require('express'); 
    

    => Requires the Express module just as you require other modules and and puts it in a variable.

    var app = express(); 
    

    => Calls the express function "express()" and puts new Express application inside the app variable (to start a new Express application). It's something like you are creating an object of a class. Where "express()" is just like class and app is it's newly created object.

    By looking the code of express below you are good to go what is really happening inside.

    File 1: index.js

    'use strict';
    
    module.exports = require('./lib/express');
    

    File 2 : lib/express.js

    'use strict';
    
    var EventEmitter = require('events').EventEmitter;
    var mixin = require('merge-descriptors');
    var proto = require('./application');
    var Route = require('./router/route');
    var Router = require('./router');
    var req = require('./request');
    var res = require('./response');
    
    /**
     * Expose `createApplication()`.
     */
    
    exports = module.exports = createApplication;
    
    function createApplication() {
      var app = function(req, res, next) {
        app.handle(req, res, next);
      };
    
      mixin(app, EventEmitter.prototype, false);
      mixin(app, proto, false);
    
      app.request = { __proto__: req, app: app };
      app.response = { __proto__: res, app: app };
      app.init();
      return app;
    }
    exports.application = proto;
    exports.request = req;
    exports.response = res;    
    exports.Route = Route;
    exports.Router = Router;
    });
    

    How require works

    When you call require('some_module') in node here is what happens:

    1. if a file called some_module.js exists in the current folder node will load that, otherwise:

    2. Node looks in the current folder for a node_modules folder with a some_module folder in it.

    3. If it doesn't find it, it will go up one folder and repeat step 2

    This cycle repeats until node reaches the root folder of the filesystem, at which point it will then check any global module folders (e.g. /usr/local/node_modules on Mac OS) and if it still doesn't find some_module it will throw an exception.

提交回复
热议问题