UNPKG

1.77 kBPlain TextView Raw
1export interface MimeBuffer extends Buffer {
2 type: string;
3 typeFull: string;
4 charset: string;
5}
6
7/**
8 * Returns a `Buffer` instance from the given data URI `uri`.
9 *
10 * @param {String} uri Data URI to turn into a Buffer instance
11 * @returns {Buffer} Buffer instance from Data URI
12 * @api public
13 */
14export 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 // strip newlines
22 uri = uri.replace(/\r?\n/g, '');
23
24 // split the URI up into the "metadata" and the "data" portions
25 const firstComma = uri.indexOf(',');
26 if (firstComma === -1 || firstComma <= 4) {
27 throw new TypeError('malformed data: URI');
28 }
29
30 // remove the "data:" scheme and parse the metadata
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 // defaults to US-ASCII only if type is not provided
48 if (!meta[0] && !charset.length) {
49 typeFull += ';charset=US-ASCII';
50 charset = 'US-ASCII';
51 }
52
53 // get the encoded data portion and decode URI-encoded chars
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 // set `.type` and `.typeFull` properties to MIME type
59 buffer.type = type;
60 buffer.typeFull = typeFull;
61
62 // set the `.charset` property
63 buffer.charset = charset;
64
65 return buffer;
66}
67
68export default dataUriToBuffer;