express简单原理

express.js

var parseUrl = require('parseurl');

exports = module.exports = createApplication;

function createApplication() {
  var app = function (req, res, next) {
    app.handle(req, res, next);
  };
  app.stack = [];
  app.handle = function handle(req, res, callback) {
    var idx = 0, match = false;
    var path = getPathname(req);
    while (match !== true && idx < this.stack.length) {
      layer = this.stack[idx++];
      match = layer.path === path;
      layer.handle(req, res, callback);
    }
  };

  app.use = function use(fn, mid) {
    var path = '/', newFn = fn;
    if (typeof fn !== 'function') {
      path = fn;
      newFn = mid;
    }

    var layer = new Layer(path, newFn);

    this.stack.push(layer);

    return this;
  };
  return app;
}

// get pathname of request
function getPathname(req) {
  try {
    return parseUrl(req).pathname;
  } catch (err) {
    return undefined;
  }
}

function Layer(path, fn) {
  this.handle = fn;
  this.path = path;
}

执行app.js

var express = require('./lib/express');
var http = require('http');
var app = new express();

app.use('/12', function (req, res, next) {
    console.log('success1');
});

app.use('/13', function (req, res, next) {
    console.log('success2');
});

var httpServer = http.createServer(app);
httpServer.listen('80');

 

posted @ 2018-03-02 13:42  洛河  阅读(162)  评论(0编辑  收藏  举报