Node.js / Express.js - How to override/intercept res.render function?

后端 未结 4 1961
囚心锁ツ
囚心锁ツ 2020-12-05 07:09

I\'m building a Node.js app with Connect/Express.js and I want to intercept the res.render(view, option) function to run some code before forwarding it on to the original r

4条回答
  •  难免孤独
    2020-12-05 08:03

    It's not a good idea to use a middleware to override a response or request method for each instance of them because the middleware is get executed for each and every request and each time it get called you use cpu as well as memory because you are creating a new function.

    As you may know javascript is a Prototype-based language and every object has a prototype, like response and request objects. By looking at code (express 4.13.4) you can find their prototypes:

    req => express.request
    res => express.response
    

    So when you want to override a method for every single instance of a response it's much much better to override it in it's prototype as it's done once is available in every instance of response:

    var app = (global.express = require('express'))();
    var render = express.response.render;
    express.response.render = function(view, options, callback) {
        // desired code
        /** here this refer to the current res instance and you can even access req for this res: **/
        console.log(this.req);
        render.apply(this, arguments);
    };
    

提交回复
热议问题