node.js - Hijack response before sent to client -


i have follow codes used middlewares

module.exports=function(callback) {     callbacks.push(callback);     return function(req,res,next) {         if (!res.hijacked) {             res.hijacked=true;         } else {             return next();         }         var send=res.send;         res.send=function(data) {             var body=data instanceof buffer ? data.tostring() : data;             var requests=[];             requests.push(function(next) {                  callbacks[0](req,res)(body,donewrapper(body,next));             });             (var i=1;i<callbacks.length;i++) {                 var hijackcallback=callbacks[i];                 requests.push(function(result,next) {                     hijackcallback(req,res)(result,donewrapper(result,next));                 });             }             var that=this;             async.waterfall(requests,function(err,result) {                 send.call(that,result);                 requests=null;                 body=null;                 that=null;             });         };         next();     }; }; 

an example of usage following:

module.exports=function() {     return hijack(function() {         return function(result,done) {             var json={};             try {                 json=json.parse(result);             } catch(e) {                 return done();             }             if (!_.isarray(json)) {                 return done();             }             var sorted=_(json).sortby(function(item) {                 if (_.isobject(item.information)) {                     return item.information.rangeindex1 || 999;                 } else {                     return 1001;                 }             });             done(sorted);         }     }); }; 

it worked fine middlewares in routes.

however,when try make app.use(hijackmiddleware()). went wrong, got can't set headers after sent error.

there no problem when used middlewares in routes,though.

have consider using express-interceptor? easy use:

var express     = require('express'); var cheerio     = require('cheerio'); var interceptor = require('express-interceptor');  var app = express();  var finalparagraphinterceptor = interceptor(function(req, res){   return {     // html responses intercepted     isinterceptable: function(){       return /text\/html/.test(res.get('content-type'));     },     // appends paragraph @ end of response body     intercept: function(body, send) {       var $document = cheerio.load(body);       $document('body').append('<p>from interceptor!</p>');        send($document.html());     }   }; })  // add interceptor middleware app.use(finalparagraphinterceptor);  app.use(express.static(__dirname + '/public/'));  app.listen(3000);