You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

38 lines
2.1 KiB

  1. # Determine the Encoding of a HTML Byte Stream
  2. This package implements the HTML Standard's [encoding sniffing algorithm](https://html.spec.whatwg.org/multipage/syntax.html#encoding-sniffing-algorithm) in all its glory. The most interesting part of this is how it pre-scans the first 1024 bytes in order to search for certain `<meta charset>`-related patterns.
  3. ```js
  4. const htmlEncodingSniffer = require("html-encoding-sniffer");
  5. const fs = require("fs");
  6. const htmlBuffer = fs.readFileSync("./html-page.html");
  7. const sniffedEncoding = htmlEncodingSniffer(htmlBuffer);
  8. ```
  9. The returned value will be a canonical [encoding name](https://encoding.spec.whatwg.org/#names-and-labels) (not a label). You might then combine this with the [whatwg-encoding](https://github.com/jsdom/whatwg-encoding) package to decode the result:
  10. ```js
  11. const whatwgEncoding = require("whatwg-encoding");
  12. const htmlString = whatwgEncoding.decode(htmlBuffer, sniffedEncoding);
  13. ```
  14. ## Options
  15. You can pass two potential options to `htmlEncodingSniffer`:
  16. ```js
  17. const sniffedEncoding = htmlEncodingSniffer(htmlBuffer, {
  18. transportLayerEncodingLabel,
  19. defaultEncoding
  20. });
  21. ```
  22. These represent two possible inputs into the [encoding sniffing algorithm](https://html.spec.whatwg.org/multipage/syntax.html#encoding-sniffing-algorithm):
  23. - `transportLayerEncodingLabel` is an encoding label that is obtained from the "transport layer" (probably a HTTP `Content-Type` header), which overrides everything but a BOM.
  24. - `defaultEncoding` is the ultimate fallback encoding used if no valid encoding is supplied by the transport layer, and no encoding is sniffed from the bytes. It defaults to `"windows-1252"`, as recommended by the algorithm's table of suggested defaults for "All other locales" (including the `en` locale).
  25. ## Credits
  26. This package was originally based on the excellent work of [@nicolashenry](https://github.com/nicolashenry), [in jsdom](https://github.com/tmpvar/jsdom/blob/16fd85618f2705d181232f6552125872a37164bc/lib/jsdom/living/helpers/encoding.js). It has since been pulled out into this separate package.