base64.ts 1.0 KB

1234567891011121314151617181920212223242526272829
  1. // Copyright (c) Microsoft Corporation. All rights reserved.
  2. // Licensed under the MIT License. See License.txt in the project root for license information.
  3. /**
  4. * Encodes a string in base64 format.
  5. * @param value the string to encode
  6. */
  7. export function encodeString(value: string): string {
  8. return Buffer.from(value).toString("base64");
  9. }
  10. /**
  11. * Encodes a byte array in base64 format.
  12. * @param value the Uint8Aray to encode
  13. */
  14. export function encodeByteArray(value: Uint8Array): string {
  15. // Buffer.from accepts <ArrayBuffer> | <SharedArrayBuffer>-- the TypeScript definition is off here
  16. // https://nodejs.org/api/buffer.html#buffer_class_method_buffer_from_arraybuffer_byteoffset_length
  17. const bufferValue = (value instanceof Buffer) ? value : Buffer.from(value.buffer as ArrayBuffer);
  18. return bufferValue.toString("base64");
  19. }
  20. /**
  21. * Decodes a base64 string into a byte array.
  22. * @param value the base64 string to decode
  23. */
  24. export function decodeString(value: string): Uint8Array {
  25. return Buffer.from(value, "base64");
  26. }