You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

index.js 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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('`uri` does not appear to be a Data URI (must begin with "data:")');
  16. }
  17. // strip newlines
  18. uri = uri.replace(/\r?\n/g, '');
  19. // split the URI up into the "metadata" and the "data" portions
  20. var firstComma = uri.indexOf(',');
  21. if (-1 === firstComma || firstComma <= 4) throw new TypeError('malformed data: URI');
  22. // remove the "data:" scheme and parse the metadata
  23. var meta = uri.substring(5, firstComma).split(';');
  24. var base64 = false;
  25. var charset = 'US-ASCII';
  26. for (var i = 0; i < meta.length; i++) {
  27. if ('base64' == meta[i]) {
  28. base64 = true;
  29. } else if (0 == meta[i].indexOf('charset=')) {
  30. charset = meta[i].substring(8);
  31. }
  32. }
  33. // get the encoded data portion and decode URI-encoded chars
  34. var data = unescape(uri.substring(firstComma + 1));
  35. var encoding = base64 ? 'base64' : 'ascii';
  36. var buffer = new Buffer(data, encoding);
  37. // set `.type` property to MIME type
  38. buffer.type = meta[0] || 'text/plain';
  39. // set the `.charset` property
  40. buffer.charset = charset;
  41. return buffer;
  42. }