UNPKG

nyx_server

Version:

Node内容发布

43 lines (38 loc) 1.09 kB
module.exports = function (code) { return function (req, res, next) { var write = res.write; var writeHead = res.writeHead; var end = res.end; var called; var buf = ''; var inject_snippet = function(string, encoding) { if (called) return; if (string !== undefined) { var body = string instanceof Buffer ? string.toString(encoding) : string; buf += body.replace(/<\/body>/, function (w) { called = true; return code + w; }); } }; res.write = function (string, encoding) { write.call(res, '', encoding); inject_snippet(string, encoding); return true; }; res.writeHead = function() { }; res.end = function (string, encoding) { res.end = end; res.write = write; // Restore writeHead res.writeHead = writeHead; inject_snippet(string, encoding); if (buf &&!res._header) { res.setHeader('content-length', Buffer.byteLength(buf, encoding)); } end.call(res, buf, encoding); }; next(); }; };