The easiest way to encode a string to base64 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 encoded const str = 'foobar'; // 2: convert string to buffer const strBuffer = Buffer.from(str); // 3: convert buffer to Base64-encoded string const encoded = strBuffer.toString('base64'); console.log(encoded); // 'Zm9vYmFy'
Unlike the btoa()
method in JavaScript, this also works with multibyte strings out of the box:
const toBase64 = (str) => Buffer.from(str).toString('base64'); console.log(toBase64('🦊')); // '8J+mig==' console.log(toBase64('こんにちは')); // '44GT44KT44Gr44Gh44Gv' console.log(toBase64('foobar')); // 'Zm9vYmFy'
Please note that the Buffer
object is within the global scope, which is why you do not need to explicitly import it using "require('buffer').Buffer
" for example.
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. Therefore, you should use Buffer.from()
instead.
Hope you found this post useful. It was published (and was last revised ). Please show your love and support by sharing this post.