PASSWORD RESET

Your destination for complete Tech news

How to do Base64 encoding in Node.js?

326 0
< 1 min read

To Base64-encode a string in Node.js, you can use the Buffer class and its .toString() method. Here’s an example:

const { Buffer } = require('buffer');

// Encode a string to Base64
const encodedString = Buffer.from('Hello, world!').toString('base64');
console.log(encodedString);  // Output: SGVsbG8sIHdvcmxkIQ==

You can also use the Buffer.from() method to decode a Base64-encoded string:

// Decode a Base64-encoded string
const decodedString = Buffer.from(encodedString, 'base64').toString();
console.log(decodedString);  // Output: Hello, world!

Alternatively, you can use the built-in Buffer global and the .toString() method to achieve the same results:

// Encode a string to Base64
const encodedString = new Buffer('Hello, world!').toString('base64');
console.log(encodedString);  // Output: SGVsbG8sIHdvcmxkIQ==

// Decode a Base64-encoded string
const decodedString = new Buffer(encodedString, 'base64').toString();
console.log(decodedString);  // Output: Hello, world!

Note: The Buffer class was designed to handle raw binary data. It has been deprecated in favor of the Buffer global in newer versions of Node.js. You should avoid using the Buffer class, as it will be removed in a future major release. Instead, you should use the Buffer global or the ArrayBuffer and TypedArray APIs.

Leave A Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.