How do I parse a data URL in Node?

2020-01-30 11:57发布

问题:

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?

回答1:

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);


回答2:

Try this

var dataUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
var buffer = new Buffer(dataUrl.split(",")[1], 'base64');


回答3:

I also met such questions (parsing and validating data URL) recently and found the following workaround: https://gist.github.com/bgrins/6194623

I created 2 packages to make working with data URL easier in the code. Here they are: https://github.com/killmenot/valid-data-url
https://github.com/killmenot/parse-data-url

Check out examples