How can I do Base64 encoding in Node.js?

Buffers can be used for taking a string or piece of data and doing Base64 encoding of the result. For example:

> console.log(Buffer.from("Hello World").toString('base64'));
> console.log(Buffer.from("SGVsbG8gV29ybGQ=", 'base64').toString('ascii'))
Hello World

Buffers are a global object, so no require is needed. Buffers created with strings can take an optional encoding parameter to specify what encoding the string is in. The available toString and Buffer constructor encodings are as follows:

‘ascii’ – for 7 bit ASCII data only. This encoding method is very
fast, and will strip the high bit if set.

‘utf8’ – Multi byte encoded
Unicode characters. Many web pages and other document formats use

‘ucs2’ – 2-bytes, little endian encoded Unicode characters. It
can encode only BMP(Basic Multilingual Plane, U+0000 – U+FFFF).

‘base64’ – Base64 string encoding.

‘binary’ – A way of encoding raw
binary data into strings by using only the first 8 bits of each
character. This encoding method is deprecated and should be avoided in
favor of Buffer objects where possible. This encoding will be removed
in future versions of Node.

Leave a Comment