From 263675f1aa00a6b31a5c5fff1b17f3fc2f6cb52b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=D0=A1=D0=BA=D0=BE=D0=B2=D0=BE=D1=80=D0=BE=D0=B4=D0=B0=20?= =?UTF-8?q?=D0=9D=D0=B8=D0=BA=D0=B8=D1=82=D0=B0=20=D0=90=D0=BD=D0=B4=D1=80?= =?UTF-8?q?=D0=B5=D0=B5=D0=B2=D0=B8=D1=87?= Date: Sat, 30 Jun 2018 22:05:44 +0300 Subject: [PATCH] io_utils: use Buffer methods instead of Blob/atob/btoa on Node.js This should fix `arrayBufferToBase64String` and `stringByteLength` tests when running on Node.js. --- src/io/io_utils.ts | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/io/io_utils.ts b/src/io/io_utils.ts index 4a75a53e62..632f79e838 100644 --- a/src/io/io_utils.ts +++ b/src/io/io_utils.ts @@ -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. * @@ -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; } @@ -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))); } @@ -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) {