How to convert dataurl to file using node js. | Parse data url in node

Many time we need to covert dataurl back to original file. Like dataurl of text file or zip file back to text file and zip file. IN nodejs we can do this without any external node module.

Example:

var fs = require('fs');
var dataurl= "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
var regex = /^data:.+\/(.+);base64,(.*)$/;
var matches = string.match(regex);
var ext = matches[1];
var data = matches[2];
var buffer = Buffer.from(data, 'base64');
fs.writeFileSync('data.' + ext, buffer);

Leave a Reply