How to Base64 Encode a String in Node.js?

The easiest way to encode a string to base64 in Node.js is to use the built-in Buffer object. For example:

const str = 'foobar';
const base64EncodedStr = Buffer.from(str).toString('base64');

console.log(base64EncodedStr); // output: 'Zm9vYmFy'

Since the Buffer object is within the global scope, you do not need to use require('buffer').Buffer.

Please note that in versions of Node.js below 6.0.0, the syntax "new Buffer(string[, encoding])" was commonly used. However, using the constructor to instantiate a new Buffer object was deprecated starting from Node.js v6.0.0 as it was vulnerable to "Remote Memory Disclosure" attacks. You should instead use Buffer.from().

Hope you found this post useful. It was published . Please show your love and support by sharing this post.