This article will show how you can decode Base64 encoded string back to binary in NodeJS.
Base64 encoding is a common technique used to represent binary data as ASCII text. In Node.js, you may encounter scenarios where you need to decode a Base64 encoded string back into binary data. The method to achieve this has evolved over different Node.js versions.
Here, we will cover the recommended approach for Node.js versions 5.11.1 and below, as well as the modern method introduced in Node.js v6.0.0 and onwards.
Using Buffer.from() (Node.js v6.0.0 and above)
Starting from Node.js v6.0.0, the constructor method for creating a Buffer from a Base64 encoded string has been deprecated. Instead, you should use the Buffer.from()
method.
Here’s how you can do it:
// Base64 encoded string var b64string = /* whatever */; // Using Buffer.from() for Node.js v6.0.0 and above var buf = Buffer.from(b64string, 'base64'); // Ta-da! 'buf' now contains the decoded binary data
Using new Buffer() (Node.js v5.11.1 and below)
For Node.js versions 5.11.1 and below, you can use the traditional new Buffer()
constructor method.
Here’s an example:
// Base64 encoded string var b64string = /* whatever */; // Using new Buffer() for Node.js v5.11.1 and below var buf = new Buffer(b64string, 'base64'); // Ta-da! 'buf' now contains the decoded binary data
Compatibility Check
To ensure compatibility across different Node.js versions, you can use the following conditional check.
// Base64 encoded string var b64string = /* whatever */; var buf; // Checking for the existence of Buffer.from() method if (typeof Buffer.from === "function") { // Node 5.10+ (including Node.js v6.0.0 and above) buf = Buffer.from(b64string, 'base64'); } else { // Older Node versions (now deprecated, v5.11.1 and below) buf = new Buffer(b64string, 'base64'); } // Ta-da! 'buf' now contains the decoded binary data, compatible across Node.js versions
By following these examples, you can decode Base64 encoded strings back to binary data in Node.js, ensuring compatibility across different versions of the runtime.