Similar to encoding a base64 string, the easiest way to decode a base64-encoded string in Node.js is to use the built-in
Buffer object. For example, you can achieve this in the following way:
// 1: define the string to be decoded const encodedStr = 'Zm9vYmFy'; // 2: convert encoded string to buffer const binaryStrBuffer = Buffer.from(encodedStr, 'base64'); // 3: convert buffer to string const decoded = binaryStrBuffer.toString('ascii'); console.log(decoded); // 'foobar'
Although encoding to an "
ascii" string is fast, it is limited to working only with strings that are encoded with single-byte binary data, which means that it may not be suitable for decoding multibyte base64-encoded strings.
For example, consider the following multibyte base64-encoded string that represents a fox emoji (
🦊), but incorrectly outputs "
p&" with "
ascii" string encoding:
const binaryStrBuffer = Buffer.from('8J+mig==', 'base64'); const decoded = binaryStrBuffer.toString('ascii')); console.log(decoded); // 'p&'
Therefore, to properly decode strings that are encoded with multibyte binary data, you should use the "
utf8" encoding method with the
Buffer.toString() method, for example, like so:
const fromBase64 = (str) => Buffer.from(str, 'base64').toString('utf8'); console.log(fromBase64('8J+mig==')); // '🦊' console.log(fromBase64('44GT44KT44Gr44Gh44Gv')); // 'こんにちは' console.log(fromBase64('Zm9vYmFy')); // 'foobar'
Hope you found this post useful. It was published . Please show your love and support by sharing this post.