Member-only story
How To Convert String To Buffer And Data URL Formats Using Client-Side JavaScript
No plugins required. Works in both browser and NodeJS (v16 onwards) environment.
In web applications, Base64 is often used to encode binary data for storage or transfer over media in ASCII text format. For instance, file transfer APIs often receive responses that are returned as binary data due to their efficiency in both storage and processing speed.
The Buffer Class In NodeJS
One of the global APIs exclusive to NodeJS is the Buffer class which serves as a convenient means to handle any binary data being sent/received. For instance, the following code snippet converts a String to ArrayBuffer and vice versa using the Buffer module in NodeJS:
const str = 'Hey. this is a string!';
const buffer = Buffer.from(str, 'utf-8'); // format: ArrayBuffer
const b64Str = Buffer.from(str, 'utf-8').toString('base64');
console.log(b64Str);
/* Expected result: */
// SGV5LiB0aGlzIGlzIGEgc3RyaW5nIQ==
const originalStr = Buffer.from(b64Str, 'base64').toString('utf-8');
console.log(originalStr);
/* Expected result: */
// Hey. this is a string!
Client-Side Browser Environment
In a browser setting, the two…