乐闻世界logo
搜索文章和话题

How to Convert a string to base64 in JavaScript. Since Btoa and atob are deprecated

1个答案

1

In JavaScript, it is possible to convert strings to Base64 encoding, and although btoa() and atob() are deprecated, they are still supported in many browsers. However, for modern development, it is recommended to use the more standard Buffer or Web API TextEncoder and TextDecoder to handle these tasks.

1. Using Buffer (for Node.js)

If you are working in a Node.js environment, you can use Buffer for Base64 encoding and decoding. Here is an example of converting a string to Base64 encoding:

javascript
const originalString = 'Hello, world!'; const base64String = Buffer.from(originalString).toString('base64'); console.log(base64String); // Output: SGVsbG8sIHdvcmxkIQ==

The reverse operation, decoding a Base64 string back to the original string:

javascript
const decodedString = Buffer.from(base64String, 'base64').toString(); console.log(decodedString); // Output: Hello, world!

2. Using TextEncoder and TextDecoder (for browsers)

In modern browsers, you can use TextEncoder and TextDecoder with Uint8Array for Base64 encoding and decoding. This approach avoids the deprecated btoa() and atob().

Here is how to encode:

javascript
const originalString = 'Hello, world!'; const encoder = new TextEncoder(); const encodedData = encoder.encode(originalString); const base64String = btoa(String.fromCharCode.apply(null, encodedData)); console.log(base64String); // Output: SGVsbG8sIHdvcmxkIQ==

Here is how to decode:

javascript
const decoder = new TextDecoder('utf-8'); const decodedData = atob(base64String).split('').map(c => c.charCodeAt(0)); const decodedString = decoder.decode(new Uint8Array(decodedData)); console.log(decodedString); // Output: Hello, world!

Both methods provide effective approaches to convert strings to Base64 encoding while avoiding deprecated features, ensuring modern code and improved compatibility.

2024年6月29日 12:07 回复

你的答案