File size: 1,770 Bytes
8a9bc9a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 | 'use strict';
/**
* Module exports.
*/
module.exports = dataUriToBuffer;
/**
* Returns a `Buffer` instance from the given data URI `uri`.
*
* @param {String} uri Data URI to turn into a Buffer instance
* @return {Buffer} Buffer instance from Data URI
* @api public
*/
function dataUriToBuffer(uri) {
if (!/^data\:/i.test(uri)) {
throw new TypeError(
'`uri` does not appear to be a Data URI (must begin with "data:")'
);
}
// strip newlines
uri = uri.replace(/\r?\n/g, '');
// split the URI up into the "metadata" and the "data" portions
var firstComma = uri.indexOf(',');
if (-1 === firstComma || firstComma <= 4) {
throw new TypeError('malformed data: URI');
}
// remove the "data:" scheme and parse the metadata
var meta = uri.substring(5, firstComma).split(';');
var type = meta[0] || 'text/plain';
var typeFull = type;
var base64 = false;
var charset = '';
for (var i = 1; i < meta.length; i++) {
if ('base64' == meta[i]) {
base64 = true;
} else {
typeFull += ';' + meta[i];
if (0 == meta[i].indexOf('charset=')) {
charset = meta[i].substring(8);
}
}
}
// defaults to US-ASCII only if type is not provided
if (!meta[0] && !charset.length) {
typeFull += ';charset=US-ASCII';
charset = 'US-ASCII';
}
// get the encoded data portion and decode URI-encoded chars
var data = unescape(uri.substring(firstComma + 1));
var encoding = base64 ? 'base64' : 'ascii';
var buffer = Buffer.from ? Buffer.from(data, encoding) : new Buffer(data, encoding);
// set `.type` and `.typeFull` properties to MIME type
buffer.type = type;
buffer.typeFull = typeFull;
// set the `.charset` property
buffer.charset = charset;
return buffer;
}
|