index.js 1.7 KB

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