| 1 | export default function dataUriToBuffer(uri) { |
| 2 | if (!/^data:/i.test(uri)) { |
| 3 | throw new TypeError( |
| 4 | '`uri` does not appear to be a Data URI (must begin with "data:")' |
| 5 | ); |
| 6 | } |
| 7 | |
| 8 | // strip newlines |
| 9 | uri = uri.replace(/\r?\n/g, ""); |
| 10 | |
| 11 | // split the URI up into the "metadata" and the "data" portions |
| 12 | const firstComma = uri.indexOf(","); |
| 13 | if (firstComma === -1 || firstComma <= 4) { |
| 14 | throw new TypeError("malformed data: URI"); |
| 15 | } |
| 16 | |
| 17 | // remove the "data:" scheme and parse the metadata |
| 18 | const meta = uri.substring(5, firstComma).split(";"); |
| 19 | |
| 20 | let charset = ""; |
| 21 | let base64 = false; |
| 22 | const type = meta[0] || "text/plain"; |
| 23 | let typeFull = type; |
| 24 | for (let i = 1; i < meta.length; i++) { |
| 25 | if (meta[i] === "base64") { |
| 26 | base64 = true; |
| 27 | } else { |
| 28 | typeFull += `;${meta[i]}`; |
| 29 | if (meta[i].indexOf("charset=") === 0) { |
| 30 | charset = meta[i].substring(8); |
| 31 | } |
| 32 | } |
| 33 | } |
| 34 | // defaults to US-ASCII only if type is not provided |
| 35 | if (!meta[0] && !charset.length) { |
| 36 | typeFull += ";charset=US-ASCII"; |
| 37 | charset = "US-ASCII"; |
| 38 | } |
| 39 | |
| 40 | // get the encoded data portion and decode URI-encoded chars |
| 41 | const encoding = base64 ? "base64" : "ascii"; |
| 42 | const data = unescape(uri.substring(firstComma + 1)); |
| 43 | const buffer = Buffer.from(data, encoding); |
| 44 | |
| 45 | // set `.type` and `.typeFull` properties to MIME type |
| 46 | buffer.type = type; |
| 47 | buffer.typeFull = typeFull; |
| 48 | |
| 49 | // set the `.charset` property |
| 50 | buffer.charset = charset; |
| 51 | |
| 52 | return buffer; |
| 53 | }; |