search

Home  >  Q&A  >  body text

javascript - NodeJS connect module use problem

I am new to nodejs. There is such a piece of code in the amazing NodeJS. Through middleware, the console printing of the code request time is too long

//request-time.js
module.exports = function(opts){
    var time = opts.time||100;
    return function(req,res,next){
        var timer = setTimeout(function(){
            console.log(req.method + " , " + req.url + " , too long!");
        },time);

        var end = res.end;
        res.end = function(chunk,encoding){
            res.end = end;                                        //
            res.end(chunk,encoding);                        //直接end(chunk,encoding)会出错
            clearTimeout(timer);
        };
        next(); 
    }
}

The comment part is my question. I guess there is something about this in the end. I don’t know if I understand it correctly.

漂亮男人漂亮男人2690 days ago957

reply all(1)I'll reply

  • phpcn_u1582

    phpcn_u15822017-07-03 11:44:55

    The term "closure" comes from the combination of a block of code to be executed (because the free variables are contained within the block, these free variables and the objects they refer to are not released) and the binding provided for the free variables. Computing environment (scope) ---Baidu Encyclopedia

    Let’s talk about the concept of closure first

    Your understanding is correct
    ,
    This is the verification process, the reason is because if you call end directly, this end is forcibly left because of this closure, so it will be automatically bound to the computer environment, so this is the later Its this is Window, so calling end directly will cause an error

    reply
    0
  • Cancelreply