Skip to content

Instantly share code, notes, and snippets.

@siteslave
Created May 12, 2024 10:14
Show Gist options
  • Save siteslave/bf05196d1757262c95c48a13fb5fc24f to your computer and use it in GitHub Desktop.
Save siteslave/bf05196d1757262c95c48a13fb5fc24f to your computer and use it in GitHub Desktop.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment