且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在 Node 中解析数据 URL?

更新时间:2023-02-23 16:54:37

使用 'base64' 编码将数据放入 Buffer 中,然后将其写入文件:

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