There might be scenarios where you need to convert an base64 string back to a file. This article will show you how.

The high level view

As an example, a base64 string representation of a png image looks like:

data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA...

To convert it back to an image, we need to:

  • Strip off the data:image/png;base64, part
  • Write the remaining string to a file using a base64 encoding.

The code

To strip off the header

I am using:

let base64String = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgA'; // Not a real image

// Remove header
let base64Image = base64String.split(';base64,').pop();

To write to a file

I am using:

import fs from 'fs';

fs.writeFile('image.png', base64Image, {encoding: 'base64'}, function(err) {
console.log('File created');
});

Don’t forget the {encoding: 'base64'} here and you will be good to go.