Sitemap

JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

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.

4 min readNov 20, 2023

--

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.

Press enter or click to view image in full size
Illustration by Author

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…

--

--

JavaScript in Plain English
JavaScript in Plain English

Published in JavaScript in Plain English

New JavaScript and Web Development content every day. Follow to join our 3.5M+ monthly readers.

Charmaine Chui
Charmaine Chui

Written by Charmaine Chui

👩‍💻 Data Analyst. Web & Software Developer. Technical Writer✍ | Trying to make the 🌐 better with baby steps👣 [ 📍SG ] LinkedIn@https://tinyurl.com/5h6cufyy

Responses (1)