dataURL.js 1.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. /*
  2. MIT License http://www.opensource.org/licenses/mit-license.php
  3. Author Natsu @xiaoxiaojx
  4. */
  5. "use strict";
  6. // data URL scheme: "data:text/javascript;charset=utf-8;base64,some-string"
  7. // http://www.ietf.org/rfc/rfc2397.txt
  8. const URIRegEx = /^data:([^;,]+)?((?:;[^;,]+)*?)(?:;(base64)?)?,(.*)$/i;
  9. /**
  10. * Decodes the provided uri.
  11. * @param {string} uri data URI
  12. * @returns {Buffer | null} decoded data
  13. */
  14. const decodeDataURI = (uri) => {
  15. const match = URIRegEx.exec(uri);
  16. if (!match) return null;
  17. const isBase64 = match[3];
  18. const body = match[4];
  19. if (isBase64) {
  20. return Buffer.from(body, "base64");
  21. }
  22. // CSS allows to use `data:image/svg+xml;utf8,<svg xmlns="http://www.w3.org/2000/svg"><rect width="100%" height="100%" style="stroke: rgb(223,224,225); stroke-width: 2px; fill: none; stroke-dasharray: 6px 3px" /></svg>`
  23. // so we return original body if we can't `decodeURIComponent`
  24. try {
  25. return Buffer.from(decodeURIComponent(body), "ascii");
  26. } catch (_) {
  27. return Buffer.from(body, "ascii");
  28. }
  29. };
  30. module.exports = {
  31. URIRegEx,
  32. decodeDataURI
  33. };