What is abab?
The abab npm package is a utility that provides Base64 encoding and decoding as well as window.atob and window.btoa polyfills for Node.js. It is designed to mimic the behavior of these methods in the web browser environment.
What are abab's main functionalities?
Base64 Encoding
This feature allows you to encode a string to Base64. The provided code sample demonstrates how to encode the string 'Hello, World!' using the btoa function.
"use strict";
const abab = require('abab');
let encodedData = abab.btoa('Hello, World!');
console.log(encodedData); // Outputs: SGVsbG8sIFdvcmxkIQ==
Base64 Decoding
This feature allows you to decode a Base64 encoded string. The provided code sample demonstrates how to decode the string 'SGVsbG8sIFdvcmxkIQ==' using the atob function.
"use strict";
const abab = require('abab');
let decodedData = abab.atob('SGVsbG8sIFdvcmxkIQ==');
console.log(decodedData); // Outputs: Hello, World!
Other packages similar to abab
base-64
The base-64 package offers a robust and performant way to encode and decode Base64 strings in Node.js. It is similar to abab but focuses solely on Base64 encoding and decoding without trying to polyfill browser-specific APIs.
js-base64
js-base64 is another popular package for encoding and decoding Base64 strings. It works in both Node.js and browser environments and provides additional features such as Unicode support and URL-safe encoding/decoding. It is more feature-rich compared to abab.
abab
A JavaScript module that implements window.atob
and window.btoa
according the forgiving-base64 algorithm in the Infra Standard. The original code was forked from w3c/web-platform-tests.
Compatibility: Node.js version 3+ and all major browsers.
Install with npm
:
npm install abab
API
btoa
(base64 encode)
const { btoa } = require('abab');
btoa('Hello, world!');
atob
(base64 decode)
const { atob } = require('abab');
atob('SGVsbG8sIHdvcmxkIQ==');
Valid characters
Per the spec, btoa
will accept strings "containing only characters in the range U+0000
to U+00FF
." If passed a string with characters above U+00FF
, btoa
will return null
. If atob
is passed a string that is not base64-valid, it will also return null
. In both cases when null
is returned, the spec calls for throwing a DOMException
of type InvalidCharacterError
.
Browsers
If you want to include just one of the methods to save bytes in your client-side code, you can require
the desired module directly.
const atob = require('abab/lib/atob');
const btoa = require('abab/lib/btoa');
Checklists
If you're submitting a PR or deploying to npm, please use the checklists in CONTRIBUTING.md
Remembering atob
vs. btoa
Here's a mnemonic that might be useful: if you have a plain string and want to base64 encode it, then decode it, btoa
is what you run before (before - btoa), and atob
is what you run after (after - atob).