node.js 如何解析 Node 中的数据 URL?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11335460/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I parse a data URL in Node?
提问by a paid nerd
I've got a data URL like this:
我有一个这样的数据 URL:
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?
将其作为二进制数据(例如 a Buffer)获取以便我可以将其写入文件的最简单方法是什么?
回答by Michelle Tilley
Put the data into a Buffer using the 'base64' encoding, then write this to a file:
使用“base64”编码将数据放入缓冲区,然后将其写入文件:
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);
回答by bert
Try this
尝试这个
var dataUrl = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg==";
var buffer = new Buffer(dataUrl.split(",")[1], 'base64');
回答by Alexey Kucherenko
I also met such questions (parsing and validating data URL) recently and found the following workaround: https://gist.github.com/bgrins/6194623
我最近也遇到了这样的问题(解析和验证数据 URL)并找到了以下解决方法: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
我创建了 2 个包,以便在代码中更轻松地使用数据 URL。它们是:
https://github.com/killmenot/valid-data-url
https://github.com/killmenot/parse-data-url
Check out examples
查看示例

