Fast Base64 Decode
fast-base64-decode is a JavaScript library providing a high-performance, low-level Base64 decoder. Its current stable version is 2.0.0, released in October 2022. The library differentiates itself by offering a direct, byte-array-oriented API, requiring the user to pre-allocate `Uint8Array` buffers and specify the exact output length. This approach is optimized for speed and memory efficiency, contrasting with higher-level alternatives like `base64-js` which handle buffer allocation automatically. It is primarily used for decoding Base64 strings where performance is critical and granular control over the output buffer is desired. The package has a moderate release cadence, with major versions aligning with significant architectural shifts like its recent conversion to an ECMAScript module.
Common errors
-
ERR_REQUIRE_ESM
cause Attempting to `require()` an ESM-only package.fixChange `const base64Decode = require('fast-base64-decode');` to `import base64Decode from 'fast-base64-decode';` and ensure your project is configured for ESM. -
TypeError: base64Decode is not a function
cause Using a default import with a CommonJS `require` call in a mixed environment, or incorrect import syntax.fixIf using ESM, ensure `import base64Decode from 'fast-base64-decode';`. If forced to use CommonJS for older Node or project setup, use `fast-base64-decode@1.x` or dynamic `import()`. -
RangeError: Offset is outside the bounds of the DataView
cause Providing a `Uint8Array` buffer that is too small for the decoded Base64 data.fixCalculate the exact required length for the decoded Base64 string and initialize the `Uint8Array` with that size. Base64 strings are generally 4 characters for every 3 bytes, plus padding, so roughly `(string.length / 4) * 3` for estimation.
Warnings
- breaking Package converted to ESM, requiring `import` syntax.
- breaking Dropped support for older Node.js versions.
- gotcha Low-level API requires pre-allocation of `Uint8Array` with correct length.
Install
-
npm install fast-base64-decode -
yarn add fast-base64-decode -
pnpm add fast-base64-decode
Imports
- base64Decode
const base64Decode = require('fast-base64-decode')import base64Decode from 'fast-base64-decode'
Quickstart
import base64Decode from 'fast-base64-decode';
// Example: Decoding 'SGVsbG8sIFdvcmxkIQ==' (which is 'Hello, World!')
// The decoded length for 'SGVsbG8sIFdvcmxkIQ==' is 13 bytes.
const encodedString = 'SGVsbG8sIFdvcmxkIQ==';
const resultBuffer = new Uint8Array(13); // Pre-allocate buffer for the decoded data
// Decode the string into the pre-allocated buffer
base64Decode(encodedString, resultBuffer);
// Convert the Uint8Array to a string for display (for demonstration)
const decodedString = new TextDecoder().decode(resultBuffer);
console.log(`Encoded: ${encodedString}`);
console.log(`Decoded: ${decodedString}`);
// Expected output: Decoded: Hello, World!