핵심 코드 분석

  • lib/express.js
  • lib/application.js, lib/response.js
  • lib/request.js, list/response.js
  • lib/view.js
  • lib/utils.js

lib/express.js

/*!
 * express
 * Copyright(c) 2009-2013 TJ Holowaychuk
 * Copyright(c) 2013 Roman Shtylman
 * Copyright(c) 2014-2015 Douglas Christopher Wilson
 * MIT Licensed
 */
 
'use strict';
 
/**
 * Module dependencies.
 */
 
var bodyParser = require('body-parser')
var EventEmitter = require('node:events').EventEmitter;
var mixin = require('merge-descriptors');
var proto = require('./application');
var Router = require('router');
var req = require('./request');
var res = require('./response');
 
/**
 * Expose `createApplication()`.
 */
 
exports = module.exports = createApplication;
 
/**
 * Create an express application.
 *
 * @return {Function}
 * @api public
 */
 
function createApplication() {
  var app = function(req, res, next) {
    app.handle(req, res, next);
  };
 
  mixin(app, EventEmitter.prototype, false);
  mixin(app, proto, false);
 
  // expose the prototype that will get set on requests
  app.request = Object.create(req, {
    app: { configurable: true, enumerable: true, writable: true, value: app }
  })
 
  // expose the prototype that will get set on responses
  app.response = Object.create(res, {
    app: { configurable: true, enumerable: true, writable: true, value: app }
  })
 
  app.init();
  return app;
}
 
/**
 * Expose the prototypes.
 */
 
exports.application = proto;
exports.request = req;
exports.response = res;
 
/**
 * Expose constructors.
 */
 
exports.Route = Router.Route;
exports.Router = Router;
 
/**
 * Expose middleware
 */
 
exports.json = bodyParser.json
exports.raw = bodyParser.raw
exports.static = require('serve-static');
exports.text = bodyParser.text
exports.urlencoded = bodyParser.urlencoded

코드는 전체 코드이며 일부를 나눠서 분석할 예정이다.

'use strict'

해당 코드는 directive prologue라고 불리는 코드이다. 해당 명령이 들어간 코드는옟날 엔진은 그냥 문자열 만들고 버리는 코드로 되며, 하위 호환 때문에 사용된다는 점을 알수 있다.

사용시 무조건 코드의 제일 윗 단에 존재해야한다.

ES 모듈과 class 본문은 자동으로 엄격 모드이기 떄문에. 해당 코드는 최신 라이브러리에서 보기 어려워 졌다.

function createApplication() {
	var app = function(req, res, next) {
		app.handle(req, res, next);
	};
	
	mixin(app, EventEmitter.prototype, false);
	mixin(app, proto, false);
	
	app.request = Object.create(req, {
		app: { configurable: true, enumerable: true, writable: true, value: app}
	})
	
	app.response = Object.create(req, {
		app: {configurable: true, enumerable: true, writable: true, value: app}
	})
	
	app.init();
	return app;
}