DEV Community

Cover image for Encode and Decode in JavaScript Using Base64Plus
A.S Nasseri
A.S Nasseri

Posted on

Encode and Decode in JavaScript Using Base64Plus

If you've ever worked with Base64 encoding and decoding in JavaScript, you know how essential it is for handling data like images, files, or API responses. However, the native JavaScript functions (btoa and atob) can sometimes feel limiting, especially when dealing with special characters or non-ASCII strings. Enter Base64Plus a lightweight and efficient npm package that simplifies Base64 encoding and decoding while addressing common pain points.

Why Choose Base64Plus?

  • Unicode Support: Handles multi-byte characters seamlessly, ensuring accurate encoding and decoding of Unicode strings.
  • Cross-Platform Compatibility: Works effortlessly in both Node.js and browser environments.
  • TypeScript Ready: Fully typed, making it ideal for modern JavaScript and TypeScript projects.
  • No Dependencies: Lightweight with zero external dependencies.

You can install Base64Plus using npm:

npm install base64plus
Enter fullscreen mode Exit fullscreen mode

Alternatively, include it directly in your HTML via a CDN:

<script src="base64Plus.umd.js"></script>
<script>
  console.log(Base64Plus.encode("Hello, World!"));
</script>
Enter fullscreen mode Exit fullscreen mode

In Node.js (CommonJS):

const Base64Plus = require('base64plus');

const originalText = "Hello, World!";
const encodedText = Base64Plus.encode(originalText);
console.log(encodedText); // Outputs: Base64 string

const decodedText = Base64Plus.decode(encodedText);
console.log(decodedText); // Outputs: "Hello, World!"
Enter fullscreen mode Exit fullscreen mode

In ES Modules:

import Base64Plus from 'base64plus';

const originalText = "こんにちは";
const encodedText = Base64Plus.encode(originalText);
console.log(encodedText); // Outputs: Base64 string

const decodedText = Base64Plus.decode(encodedText);
console.log(decodedText); // Outputs: "こんにちは"
Enter fullscreen mode Exit fullscreen mode

Conclusion

Base64Plus simplifies the process of encoding and decoding Base64, especially when dealing with Unicode characters. Its versatility across different environments and support for modern development practices make it a valuable tool for developers. For more information and to access the source code, visit the Base64Plus GitHub repository.

Top comments (0)