Encode Base64 in Node.js

In this short article, we’ll learn how to convert strings or text into base64 in Node.js.

Base64 Encoding in Node.js

Buffer objects are utilized to represent a fixed-length sequence of bytes. A large number of Node.js APIs support buffers.

A string can be converted into a sequence of bytes using the Buffer.from() method, which takes the string to be converted and the string’s current encoding. You can specify this encoding as UTF8.

The JavaScript class Uint8Array is a Buffer class subclass, which adds new methods to meet various use situations. Simple Uint8Arrays are accepted by Node.js APIs as long as buffers are supported.

Although the Buffer class is accessible in the global scope, it is still advised to use an import or need a statement to explicitly reference it. Decoding is turning a buffer into a string using any method, and encoding is turning a string into a buffer.

The function toString() method can then be used to return the converted bytes as a base64. The encoding required during conversion is specified via a parameter accepted by this procedure.

The following are additional binary-to-text encodings that Node.js supports.

  1. base64
  2. base64url
  3. hex

The Base64 encoding accepts the URL and Filename Safe Alphabet described in RFC 4648 Section 5 when constructing a buffer from a string. Whitespace in the base64-encoded string, including spaces, tabs, and newlines.

Let’s understand it with a simple example.

Code:

console.log(Buffer.from("Hello DelftStack Readers!").toString('base64'));
console.log(Buffer.from("SGVsbG8gRGVsZnRTdGFjayBSZWFkZXJzIQ==", 'base64').toString('ascii'));

We passed the text to buffer and expected it to encode it into base64. In the next line of code, we are decoding the buffer from base64 to ascii which is your plain text.

Try to run the above example in a compiler that supports Node.js,

Output:

SGVsbG8gRGVsZnRTdGFjayBSZWFkZXJzIQ==
Hello DelftStack Readers!

Run Demo

Related Article - Node.js Encode

  • Encode URL in Node.js