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 |
To write to a file
I am using:
import fs from 'fs'; |
Don’t forget the {encoding: 'base64'}
here and you will be good to go.