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.

data.js 1.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /**
  2. * Module dependencies.
  3. */
  4. var crypto = require('crypto');
  5. var Readable = require('readable-stream');;
  6. var dataUriToBuffer = require('data-uri-to-buffer');
  7. var NotModifiedError = require('./notmodified');
  8. var debug = require('debug')('get-uri:data');
  9. /**
  10. * Module exports.
  11. */
  12. module.exports = get;
  13. /**
  14. * Returns a Readable stream from a "data:" URI.
  15. *
  16. * @api protected
  17. */
  18. function get (parsed, opts, fn) {
  19. var uri = parsed.href;
  20. var cache = opts.cache;
  21. // need to create a SHA1 hash of the URI string, for cacheability checks
  22. // in future `getUri()` calls with the same data URI passed in.
  23. var shasum = crypto.createHash('sha1');
  24. shasum.update(uri);
  25. var hash = shasum.digest('hex');
  26. debug('generated SHA1 hash for "data:" URI: %o', hash);
  27. // check if the cache is the same "data:" URI that was previously passed in.
  28. if (cache && cache.hash == hash) {
  29. debug('got matching cache SHA1 hash: %o', hash);
  30. fn(new NotModifiedError());
  31. } else {
  32. debug('creating Readable stream from "data:" URI buffer');
  33. var buf = dataUriToBuffer(uri, opts);
  34. var rs = new Readable();
  35. rs._read = read(buf);
  36. buf = null;
  37. rs.hash = hash;
  38. fn(null, rs);
  39. }
  40. }
  41. /**
  42. * Function that returns a Readable `_read` function implementation.
  43. *
  44. * @api private
  45. */
  46. function read (buf) {
  47. return function (n) {
  48. this.push(buf);
  49. this.push(null);
  50. buf = null;
  51. };
  52. }