简体   繁体   English

如何在 Node 中解析数据 URL?

[英]How do I parse a data URL in Node?

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?将其作为二进制数据(例如Buffer )获取以便将其写入文件的最简单方法是什么?

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

Try this试试这个

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

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.我创建了 2 个包,以便在代码中更轻松地使用数据 URL。 Here they are: https://github.com/killmenot/valid-data-url它们是: https : //github.com/killmenot/valid-data-url
https://github.com/killmenot/parse-data-url https://github.com/killmenot/parse-data-url

Check out examples查看示例

This method works for me这种方法对我有用




function dataURItoBlob(dataURI) {
  // convert base64 to raw binary data held in a string
  var data = dataURI.split(',')[1]; 
  var byteString = Buffer.from(data, "base64");

  // separate out the mime component
  var mimeString = dataURI.split(",")[0].split(":")[1].split(";")[0];

  // write the ArrayBuffer to a blob, and you're done
  var blob = new Blob([byteString], { type: mimeString  });
  return blob;
}

to use使用

var uri = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=='; 
dataURItoBlob(uri)

I was looking into the sources of Node.js and stumbled upon this code that decodes a data URL into a Buffer .我正在查看 Node.js 的源代码并偶然发现了这段将数据 URL 解码为Buffer Although the function is not public and exclusively intended to parse encoded ES modules, it sheds light on aspects of data URLs that are apparently not considered by some other answers: the content of data URLs must not be base64 encoded and may be URL encoded , and it may even be unencoded.虽然该函数不是公开的并且专门用于解析编码的 ES 模块,但它阐明了一些其他答案显然没有考虑的数据 URL 的方面:数据 URL 的内容不能是 base64 编码的,并且可以是 URL 编码的,并且它甚至可能是未编码的。

Essentially, the Node.js logic boils down to something like the code below plus error handling:本质上,Node.js 逻辑可以归结为如下代码加上错误处理:

const parsed = new URL(url);
const match = /^[^/]+\/[^,;]+(?:[^,]*?)(;base64)?,([\s\S]*)$/.exec(parsed.pathname);
const { 1: base64, 2: body } = match;
const buffer = Buffer.from(decodeURIComponent(body), base64 ? 'base64' : 'utf8');

This will correctly handle different encodings of a Javascript file with the content console.log("Node.js");这将正确处理具有内容console.log("Node.js");的 Javascript 文件的不同编码console.log("Node.js"); :

  • data:text/javascript,console.log("Node.js");数据:text/javascript,console.log("Node.js");
  • data:text/javascript,console.log(%22Node.js%22)%3B数据:文本/javascript,console.log(%22Node.js%22)%3B
  • data:text/javascript;base64,Y29uc29sZS5sb2coIk5vZGUuanMiKTs=数据:文本/javascript;base64,Y29uc29sZS5sb2coIk5vZGUuanMiKTs=

The resulting buffer can be converted into a string if required with buffer.toString() .如果需要,可以使用buffer.toString()将结果缓冲区转换为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM