What is base64-js?
The base64-js npm package is a utility for encoding and decoding data to and from base64, a binary-to-text encoding scheme that represents binary data in an ASCII string format. It is commonly used to encode data in web applications.
What are base64-js's main functionalities?
Encoding a byte array to a base64 string
This feature allows you to convert a byte array (Uint8Array) into a base64 encoded string.
"use strict";\nconst base64js = require('base64-js');\nconst bytes = new Uint8Array([72, 101, 108, 108, 111]);\nconst base64String = base64js.fromByteArray(bytes);\nconsole.log(base64String); // Outputs: 'SGVsbG8='
Decoding a base64 string to a byte array
This feature allows you to convert a base64 encoded string back into a byte array (Uint8Array).
"use strict";\nconst base64js = require('base64-js');\nconst base64String = 'SGVsbG8=';\nconst bytes = base64js.toByteArray(base64String);\nconsole.log(bytes); // Outputs: Uint8Array [72, 101, 108, 108, 111]
Other packages similar to base64-js
buffer
The 'buffer' package provides a way to handle binary data in Node.js. It includes methods for encoding and decoding base64. It is more comprehensive than base64-js as it is a part of Node.js core and handles more than just base64 encoding.
js-base64
The 'js-base64' package is another utility for encoding and decoding base64. It works both in the browser and in Node.js, and it also provides additional functionalities like Unicode string support, which base64-js does not have.
Intro
base64-js
does basic base64 encoding/decoding in pure JS. Many browsers already have this functionality, but it is for text data, not all-purpose binary data.
Sometimes encoding/decoding binary data in the browser is useful, and that is what this module does.
API
base64-js
has two exposed functions, toByteArray
and fromByteArray
, which both take a single argument.
- toByteArray- Takes a base64 string and returns a byte array
- fromByteArray- Takes a byte array and returns a base64 string