How to use brotli - 10 common examples

To help you get started, we’ve selected a few brotli examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github codemanki / cloudscraper / test / test-brotli.js View on Github external
(zlib.brotliCompressSync ? it.skip : it)('[external] decompress() should produce the expected result', function () {
    const input = helper.getFixture('captcha.html');
    // Try increasing the timeout if this fails on your system.
    const data = require('brotli').compress(Buffer.from(input, 'utf8'));
    const result = brotli.decompress(Buffer.from(data));

    expect(result).to.be.instanceof(Buffer);
    expect(result.toString('utf8')).to.equal(input);
  });
github DevExpress / testcafe-hammerhead / src / processing / encoding / index.ts View on Github external
export async function decodeContent (content: Buffer, encoding: string, charset: Charset) {
    if (encoding === GZIP_CONTENT_ENCODING) {
        // NOTE: https://github.com/request/request/pull/2492/files
        // Be more lenient with decoding compressed responses, since (very rarely)
        // servers send slightly invalid gzip responses that are still accepted
        // by common browsers.
        // Always using Z_SYNC_FLUSH is what cURL does.
        // GH-1915
        content = await gunzip(content, { flush: zlib.Z_SYNC_FLUSH, finishFlush: zlib.Z_SYNC_FLUSH });
    }

    else if (encoding === DEFLATE_CONTENT_ENCODING)
        content = await inflateWithFallback(content);

    else if (encoding === BROTLI_CONTENT_ENCODING)
        content = Buffer.from(require('brotli').decompress(content));

    charset.fromBOM(content);

    return charsetEncoder.decode(content, charset.get());
}
github cb1kenobi / snooplogg / scripts / gen-brightness-lookup.js View on Github external
results[brightness] = [];
			}
			results[brightness].push(r, g, b);
		}
	}
}

console.log('Writing lookup files...');
for (brightness of Object.keys(results)) {
	let colors = results[brightness];
	let before;
	let after;

	do {
		before = Buffer.from(colors);
		after = brotli.compress(before);
		if (!after) {
			// when brightness=255, there's only 1 color (3 bytes) and it's not enough bytes to make brotli happy
			colors = colors.concat(colors.slice(0, 3));
		}
	} while (!after);

	const blen = before.length;
	const alen = after.length;

	totalBefore += blen;
	totalAfter += alen;

	console.log('%s\t%s => %s\t(%s\%)', brightness, blen, alen, Math.round((blen - alen) / blen * 1000) / 10);

	fs.writeFileSync(
		`${outputDir}/${brightness}.br`,
github airtasker / proxay / src / persistence.ts View on Github external
function unserialiseBuffer(persisted: PersistedBuffer): Buffer {
  let buffer;
  switch (persisted.encoding) {
    case "base64":
      buffer = Buffer.from(persisted.data, "base64");
      break;
    case "utf8":
      buffer = Buffer.from(persisted.data, "utf8");
      if (persisted.compression === "br") {
        // TODO: Find a workaround for the new compressed message not necessarily
        // being identical to what was originally sent (update Content-Length?).
        const compressed = brotli.compress(buffer);
        if (compressed) {
          buffer = Buffer.from(compressed);
        } else {
          throw new Error(`Brotli compression failed!`);
        }
      }
      if (persisted.compression === "gzip") {
        // TODO: Find a workaround for the new compressed message not necessarily
        // being identical to what was originally sent (update Content-Length?).
        buffer = gzipSync(buffer);
      }
      break;
    default:
      throw new Error(`Unsupported encoding!`);
  }
  return buffer;
github bramstein / opentype / src / opentype.js View on Github external
transformVersion = 0;

        var transformLength = rb.read(Type.BASE128);
      }

      totalSize += origLength;

      index.push({
        flags: flag,
        tag: tag,
        origLength: origLength
      });
    }

    // TODO: Upgrade to Node v6.x so we can use Buffer.from.
    var data = new Buffer(brotli.decompress(buffer.slice(rb.byteOffset, rb.byteOffset + totalSize)));
    var offset = 0;

    index.forEach(function (table) {
      font.tables[table.tag] = data.slice(offset, offset + util.pad(table.origLength));
      offset += table.origLength;
    });
  } else if (signature === Format.TRUETYPE || signature === Format.OPENTYPE) {
    font.header = rb.read(sfnt.Header);
    var index = rb.readArray(sfnt.OffsetTable, font.header.numTables);

    index.forEach(function (table) {
      font.tables[table.tag] = buffer.slice(table.offset, table.offset + util.pad(table.length));
    });
  }

  for (var table in TABLES) {
github airtasker / proxay / src / persistence.ts View on Github external
export function serialiseBuffer(
  buffer: Buffer,
  headers: Headers
): PersistedBuffer {
  const header = headers["content-encoding"];
  const contentEncoding = typeof header === "string" ? header : undefined;
  const originalBuffer = buffer;
  let compression: CompressionAlgorithm = "none";
  if (contentEncoding === "br") {
    buffer = Buffer.from(brotli.decompress(buffer));
    compression = "br";
  }
  if (contentEncoding === "gzip") {
    buffer = gunzipSync(buffer);
    compression = "gzip";
  }
  const utf8Representation = buffer.toString("utf8");
  try {
    // Can it be safely stored and recreated in YAML?
    const recreatedBuffer = Buffer.from(
      yaml.safeLoad(yaml.safeDump(utf8Representation)),
      "utf8"
    );
    if (Buffer.compare(buffer, recreatedBuffer) === 0) {
      // Yes, we can store it in YAML.
      return {
github alibaba / anyproxy / lib / requestHandler.js View on Github external
});
            } else if (isServerDeflated && originContentLen) {
              refactContentEncoding();
              zlib.inflateRaw(serverResData, (err, buff) => {
                if (err) {
                  rejectParsing(err);
                } else {
                  fulfill(buff);
                }
              });
            } else if (isBrotlied && originContentLen) {
              refactContentEncoding();

              try {
                // an Unit8Array returned by decompression
                const result = brotliTorb.decompress(serverResData);
                fulfill(Buffer.from(result));
              } catch (e) {
                rejectParsing(e);
              }
            } else {
              fulfill(serverResData);
            }
          }
        }).then((serverResData) => {
          resolve({
github alibaba / anyproxy / lib / requestHandler / UserReqHandler.js View on Github external
});
            } else if (isServerDeflated && originContentLen) {
              refactContentEncoding();
              zlib.inflateRaw(serverResData, (err, buff) => { // TODO test case to cover
                if (err) {
                  rejectParsing(err);
                } else {
                  fulfill(buff);
                }
              });
            } else if (isBrotlied && originContentLen) {
              refactContentEncoding();

              try {
                // an Unit8Array returned by decompression
                const result = brotliTorb.decompress(serverResData);
                fulfill(Buffer.from(result));
              } catch (e) {
                rejectParsing(e);
              }
            } else {
              fulfill(serverResData);
            }
          }
        }).then((serverResData) => {
          resolve({
github foliojs / fontkit / src / WOFF2Font.js View on Github external
_decompress() {
    // decompress data and setup table offsets if we haven't already
    if (!this._decompressed) {
      this.stream.pos = this._dataPos;
      let buffer = this.stream.readBuffer(this.directory.totalCompressedSize);

      let decompressedSize = 0;
      for (let tag in this.directory.tables) {
        let entry = this.directory.tables[tag];
        entry.offset = decompressedSize;
        decompressedSize += (entry.transformLength != null) ? entry.transformLength : entry.length;
      }

      let decompressed = brotli(buffer, decompressedSize);
      if (!decompressed) {
        throw new Error('Error decoding compressed data in WOFF2');
      }

      this.stream = new r.DecodeStream(new Buffer(decompressed));
      this._decompressed = true;
    }
  }
github ionic-team / stencil / test / .scripts / file-size-profile.js View on Github external
function getBuildFileSize(filePath) {
  try {
    const content = fs.readFileSync(filePath);
    let fileName = path.basename(filePath);

    let brotliSize;
    let gzipSize;
    let minifiedSize;

    if (content.length > 0) {
      const brotliResult = brotli.compress(content);
      brotliSize = brotliResult ? brotliResult.length : 0;
      gzipSize = zlib.gzipSync(content, { level: 9 }).length;
      minifiedSize = fs.statSync(filePath).size;
    } else {
      brotliSize = gzipSize = minifiedSize = 0;
    }
    totalBrotli += brotliSize;
    totalGzip += gzipSize;
    totalMinify += minifiedSize;

    return render(fileName, brotliSize, gzipSize, minifiedSize);

  } catch (e) {
    console.error(e);
    return '';
  }

brotli

A port of the Brotli compression algorithm as used in WOFF2

MIT
Latest version published 2 years ago

Package Health Score

67 / 100
Full package analysis