diff --git a/HISTORY.md b/HISTORY.md index 7f625d08..3d224eda 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -1,3 +1,7 @@ +unreleased +========== + * Use `res.headersSent` when available + 1.7.5 / 2024-10-31 ========== diff --git a/index.js b/index.js index c7494e71..332e4ab5 100644 --- a/index.js +++ b/index.js @@ -80,7 +80,7 @@ function compression (options) { return false } - if (!this._header) { + if (!headersSent(res)) { this._implicitHeader() } @@ -94,7 +94,7 @@ function compression (options) { return false } - if (!this._header) { + if (!headersSent(res)) { // estimate the length if (!this.getHeader('Content-Length')) { length = chunkLength(chunk, encoding) @@ -281,3 +281,17 @@ function toBuffer (chunk, encoding) { ? chunk : Buffer.from(chunk, encoding) } + +/** + * Determine if the response headers have been sent. + * + * @param {object} res + * @returns {boolean} + * @private + */ + +function headersSent (res) { + return typeof res.headersSent !== 'boolean' + ? Boolean(res._header) + : res.headersSent +}