binaryToBase64.js 755 B

1234567891011121314151617181920212223242526272829
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @format
  8. * @flow
  9. */
  10. 'use strict';
  11. const base64 = require('base64-js');
  12. function binaryToBase64(data: ArrayBuffer | $ArrayBufferView): any {
  13. if (data instanceof ArrayBuffer) {
  14. data = new Uint8Array(data);
  15. }
  16. if (data instanceof Uint8Array) {
  17. return base64.fromByteArray(data);
  18. }
  19. if (!ArrayBuffer.isView(data)) {
  20. throw new Error('data must be ArrayBuffer or typed array');
  21. }
  22. const {buffer, byteOffset, byteLength} = data;
  23. return base64.fromByteArray(new Uint8Array(buffer, byteOffset, byteLength));
  24. }
  25. module.exports = binaryToBase64;