Skip to content
This repository has been archived by the owner on Aug 15, 2019. It is now read-only.

Commit

Permalink
io_utils: use Buffer methods instead of Blob/atob/btoa on Node.js
Browse files Browse the repository at this point in the history
This should fix `arrayBufferToBase64String` and `stringByteLength`
tests when running on Node.js.
  • Loading branch information
ChALkeR committed Jun 30, 2018
1 parent b7efcd9 commit 263675f
Showing 1 changed file with 17 additions and 0 deletions.
17 changes: 17 additions & 0 deletions src/io/io_utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,13 @@ export function concatenateTypedArrays(xs: TypedArray[]): ArrayBuffer {
return y.buffer;
}

// Use Buffer on Node.js instead of Blob/btoa/atob
const useNodeBuffer = typeof Buffer !== 'undefined' && (
typeof Blob === 'undefined' ||
typeof atob === 'undefined' ||
typeof btoa === 'undefined'
);

/**
* Calculate the byte length of a JavaScript string.
*
Expand All @@ -152,6 +159,9 @@ export function concatenateTypedArrays(xs: TypedArray[]): ArrayBuffer {
* @returns Byte length.
*/
export function stringByteLength(str: string): number {
if (useNodeBuffer) {
return Buffer.byteLength(str);
}
return new Blob([str]).size;
}

Expand All @@ -162,6 +172,9 @@ export function stringByteLength(str: string): number {
* @returns A string that base64-encodes `buffer`.
*/
export function arrayBufferToBase64String(buffer: ArrayBuffer): string {
if (useNodeBuffer) {
return Buffer.from(buffer).toString('base64');
}
return btoa(String.fromCharCode.apply(null, new Uint8Array(buffer)));
}

Expand All @@ -172,6 +185,10 @@ export function arrayBufferToBase64String(buffer: ArrayBuffer): string {
* @returns Decoded `ArrayBuffer`.
*/
export function base64StringToArrayBuffer(str: string): ArrayBuffer {
if (useNodeBuffer) {
const buf = Buffer.from(str, 'base64');
return buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
}
const s = atob(str);
const buffer = new Uint8Array(s.length);
for (let i = 0; i < s.length; ++i) {
Expand Down

0 comments on commit 263675f

Please sign in to comment.