base64.ts 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /**
  2. * [Base64 encoding](link-wiki-base64) using 6-bit words to encode
  3. * arbitrary bytes into a string using 65 printable symbols, the
  4. * upper-case and lower-case alphabet, the digits ``0`` through ``9``,
  5. * ``"+"`` and ``"/"`` with the ``"="`` used for padding.
  6. *
  7. * @_subsection: api/utils:Base64 Encoding [about-base64]
  8. */
  9. import { getBytes, getBytesCopy } from "./data.js";
  10. import type { BytesLike } from "./data.js";
  11. /**
  12. * Decodes the base-64 encoded %%value%%.
  13. *
  14. * @example:
  15. * // The decoded value is always binary data...
  16. * result = decodeBase64("SGVsbG8gV29ybGQhIQ==")
  17. * //_result:
  18. *
  19. * // ...use toUtf8String to convert it to a string.
  20. * toUtf8String(result)
  21. * //_result:
  22. *
  23. * // Decoding binary data
  24. * decodeBase64("EjQ=")
  25. * //_result:
  26. */
  27. export function decodeBase64(value: string): Uint8Array {
  28. return getBytesCopy(Buffer.from(value, "base64"));
  29. };
  30. /**
  31. * Encodes %%data%% as a base-64 encoded string.
  32. *
  33. * @example:
  34. * // Encoding binary data as a hexstring
  35. * encodeBase64("0x1234")
  36. * //_result:
  37. *
  38. * // Encoding binary data as a Uint8Array
  39. * encodeBase64(new Uint8Array([ 0x12, 0x34 ]))
  40. * //_result:
  41. *
  42. * // The input MUST be data...
  43. * encodeBase64("Hello World!!")
  44. * //_error:
  45. *
  46. * // ...use toUtf8Bytes for this.
  47. * encodeBase64(toUtf8Bytes("Hello World!!"))
  48. * //_result:
  49. */
  50. export function encodeBase64(data: BytesLike): string {
  51. return Buffer.from(getBytes(data)).toString("base64");
  52. }