mygzip.js 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. /**!
  2. * koa-gzip - index.js
  3. *
  4. * Copyright(c) 2014
  5. * MIT Licensed
  6. *
  7. * Authors:
  8. * fengmk2 <fengmk2@gmail.com> (http://fengmk2.github.com)
  9. */
  10. "use strict";
  11. /**
  12. * Module dependencies.
  13. */
  14. var zlib = require('zlib');
  15. var thunkify = require('thunkify-wrap');
  16. var _gzip = thunkify(zlib.gzip);
  17. module.exports = function (options) {
  18. options = options || {};
  19. // https://developers.google.com/speed/docs/best-practices/payload#GzipCompression
  20. options.minLength = Number(options.minLength) || 150;
  21. return function *gzip(next) {
  22. yield *next;
  23. var body = this.body;
  24. if (200 !== this.status
  25. || this.no_use_gzip
  26. || !body
  27. || this.acceptsEncodings('gzip') !== 'gzip'
  28. || this.response.header['content-encoding']) {
  29. return;
  30. }
  31. // TODO: Stream body
  32. if ('function' === typeof body.pipe) {
  33. this.set('content-encoding', 'gzip');
  34. this.remove('content-length');
  35. this.body = body.pipe(zlib.createGzip());
  36. return;
  37. }
  38. if (typeof body === 'string') {
  39. body = new Buffer(body);
  40. } else if (!Buffer.isBuffer(body)) {
  41. body = new Buffer(JSON.stringify(body));
  42. }
  43. if (body.length < options.minLength) {
  44. return;
  45. }
  46. var buf = yield _gzip(body);
  47. if (buf.length > body.length) {
  48. return;
  49. }
  50. this.set('content-encoding', 'gzip');
  51. this.body = buf;
  52. };
  53. };