• app.listen(3000)的源码 和callback


    
    
      const http = require('http');
     listen(...args) {
        debug('listen');
        const server = http.createServer(this.callback());
        return server.listen(...args);
      }
    const compose = require('koa-compose');
     /**
       * Return a request handler callback
       * for node's native http server.
       *
       * @return {Function}
       * @api public
       */
    
      callback() {
        const fn = compose(this.middleware);  //合并中间件
    
        if (!this.listenerCount('error')) this.on('error', this.onerror);  //有error消息, 比如app.on('error',(err)=>console.log('err',err))
    
        const handleRequest = (req, res) => {
          const ctx = this.createContext(req, res);
          return this.handleRequest(ctx, fn);
        };
    
        return handleRequest;
      }
      /**
       * Initialize a new context.
       *
       * @api private
       */
    
      createContext(req, res) {
        const context = Object.create(this.context);
        const request = context.request = Object.create(this.request);
        const response = context.response = Object.create(this.response);
        context.app = request.app = response.app = this;
        context.req = request.req = response.req = req;
        context.res = request.res = response.res = res;
        request.ctx = response.ctx = context;
        request.response = response;
        response.request = request;
        context.originalUrl = request.originalUrl = req.url;
        context.state = {};
        return context;
      }
     /**
       * Handle request in callback.
       *
       * @api private
       */
    
      handleRequest(ctx, fnMiddleware) {
        const res = ctx.res;
        res.statusCode = 404;
        const onerror = err => ctx.onerror(err);
        const handleResponse = () => respond(ctx);
        onFinished(res, onerror);
        return fnMiddleware(ctx).then(handleResponse).catch(onerror);
      }
     /**
       * Return a request handler callback
       * for node's native http server.
       *
       * @return {Function}
       * @api public
       */

      callback() {
        const fn = compose(this.middleware);

        if (!this.listenerCount('error')) this.on('error'this.onerror);

        const handleRequest = (reqres=> {
          const ctx = this.createContext(reqres);
          return this.handleRequest(ctxfn);
        };

        return handleRequest;
      }
  • 相关阅读:
    2018.10.05模拟总结
    CentOS 7 分区方案
    Linux讲解之定时任务
    TrueCrypt与CryptSetup双系统全盘加密(图文)
    使用LUKS加密你的磁盘
    使用LUKS加密你的磁盘
    本文介绍使用windows系统自带的远程桌面mstsc连接Centos 7.x远程桌面的基本方法。
    Xrdp
    CentOS7开放端口以及常用的使用命令记录整理
    【Python成长之路】装逼的一行代码:快速共享文件
  • 原文地址:https://www.cnblogs.com/TTblog5/p/13097252.html
Copyright © 2020-2023  润新知