Node.js Base64 Encoding Example

The simplest way to convert a string to Base64 encoded format in Node.js is via the built-in Buffer class.

The Buffer class is within the global scope in Node.js. That means, you can use it directly without any require statement.

Internally, a Buffer object is an immutable array of integers. The Buffer class implements the Uint8Array API. It is capable of performing many different encodings and decodings.

Base64 encoding a String in Node.js

The following example demonstrates how to encode a string to Base64 encoded format in Node.js using Buffer class -

'use strict';

let data = 'Hello @ World!';

let buf = Buffer.from(data);
let encodedData = buf.toString('base64');

console.log(encodedData);
$ node base64_encode.js
SGVsbG8gQCBXb3JsZCE=

Base64 encoding a File in Node.js

The following example shows how to convert a binary data to base64 encoded format:

'use strict';

const fs = require('fs');

fs.readFile('./sample-file.png', (err, data) => {
  if (err) throw err;
  let encodedData = data.toString('base64');
  console.log(encodedData);
});

Also Read: Base64 Decoding in Node.js

References