Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I parse a data URL in Node?

I've got a data URL like this:

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

What's the easiest way to get this as binary data (say, a Buffer) so I can write it to a file?

like image 931
a paid nerd Avatar asked Jul 04 '12 21:07

a paid nerd


People also ask

How do you parse a URL?

The url. parse() method takes a URL string, parses it, and it will return a URL object with each part of the address as properties. Parameters: This method accepts three parameters as mentioned above and described below: urlString: It holds the URL string which needs to parse.

What is URL parse ()?

URL Parsing. The URL parsing functions focus on splitting a URL string into its components, or on combining URL components into a URL string.

What is parse in Nodejs?

parse() The JSON. parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.


2 Answers

Put the data into a Buffer using the 'base64' encoding, then write this to a file:

var fs = require('fs'); var string = "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); 
like image 80
Michelle Tilley Avatar answered Sep 23 '22 17:09

Michelle Tilley


Try this

var dataUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="; var buffer = new Buffer(dataUrl.split(",")[1], 'base64'); 
like image 41
bert Avatar answered Sep 23 '22 17:09

bert