index.js 1.4 KB

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