1 | export interface MimeBuffer extends Buffer {
|
2 | type: string;
|
3 | typeFull: string;
|
4 | charset: string;
|
5 | }
|
6 |
|
7 |
|
8 |
|
9 |
|
10 |
|
11 |
|
12 |
|
13 |
|
14 | export function dataUriToBuffer(uri: string): MimeBuffer {
|
15 | if (!/^data:/i.test(uri)) {
|
16 | throw new TypeError(
|
17 | '`uri` does not appear to be a Data URI (must begin with "data:")'
|
18 | );
|
19 | }
|
20 |
|
21 |
|
22 | uri = uri.replace(/\r?\n/g, '');
|
23 |
|
24 |
|
25 | const firstComma = uri.indexOf(',');
|
26 | if (firstComma === -1 || firstComma <= 4) {
|
27 | throw new TypeError('malformed data: URI');
|
28 | }
|
29 |
|
30 |
|
31 | const meta = uri.substring(5, firstComma).split(';');
|
32 |
|
33 | let charset = '';
|
34 | let base64 = false;
|
35 | const type = meta[0] || 'text/plain';
|
36 | let typeFull = type;
|
37 | for (let i = 1; i < meta.length; i++) {
|
38 | if (meta[i] === 'base64') {
|
39 | base64 = true;
|
40 | } else {
|
41 | typeFull += `;${ meta[i]}`;
|
42 | if (meta[i].indexOf('charset=') === 0) {
|
43 | charset = meta[i].substring(8);
|
44 | }
|
45 | }
|
46 | }
|
47 |
|
48 | if (!meta[0] && !charset.length) {
|
49 | typeFull += ';charset=US-ASCII';
|
50 | charset = 'US-ASCII';
|
51 | }
|
52 |
|
53 |
|
54 | const encoding = base64 ? 'base64' : 'ascii';
|
55 | const data = unescape(uri.substring(firstComma + 1));
|
56 | const buffer = Buffer.from(data, encoding) as MimeBuffer;
|
57 |
|
58 |
|
59 | buffer.type = type;
|
60 | buffer.typeFull = typeFull;
|
61 |
|
62 |
|
63 | buffer.charset = charset;
|
64 |
|
65 | return buffer;
|
66 | }
|
67 |
|
68 | export default dataUriToBuffer;
|