Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: support brotli #150

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
1 change: 1 addition & 0 deletions README.md
Expand Up @@ -11,6 +11,7 @@ The following compression codings are supported:

- deflate
- gzip
- br

## Install

Expand Down
25 changes: 18 additions & 7 deletions index.js
Expand Up @@ -38,7 +38,7 @@ module.exports.filter = shouldCompress
var cacheControlNoTransformRegExp = /(?:^|,)\s*?no-transform\s*?(?:,|$)/

/**
* Compress response data with gzip / deflate.
* Compress response data with gzip / deflate / brotli.
*
* @param {Object} [options]
* @return {Function} middleware
Expand Down Expand Up @@ -175,11 +175,20 @@ function compression (options) {

// compression method
var accept = accepts(req)
var method = accept.encoding(['gzip', 'deflate', 'identity'])
var methods = ['gzip', 'deflate', 'identity']
var preferredMethods = ['gzip']

if (zlib.createBrotliDecompress) {
methods.unshift('br')
preferredMethods.unshift('br')
}

var method = accept.encoding(methods)

// we really don't prefer deflate
if (method === 'deflate' && accept.encoding(['gzip'])) {
method = accept.encoding(['gzip', 'identity'])
if (method === 'deflate' && accept.encoding(preferredMethods)) {
preferredMethods.push('identity')
method = accept.encoding(preferredMethods)
}

// negotiation failed
Expand All @@ -190,9 +199,11 @@ function compression (options) {

// compression stream
debug('%s compression', method)
stream = method === 'gzip'
? zlib.createGzip(opts)
: zlib.createDeflate(opts)
switch (method) {
case 'br': stream = zlib.createBrotliDecompress(opts); break
clarkdo marked this conversation as resolved.
Show resolved Hide resolved
case 'gzip': stream = zlib.createGzip(opts); break
case 'deflate': stream = zlib.createDeflate(opts); break
}

// add buffered listeners to stream
addListeners(stream, stream.on, listeners)
Expand Down