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.8KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. 'use strict';
  2. /**
  3. * Module dependencies.
  4. */
  5. var parse = require('url').parse;
  6. var debug = require('debug')('get-uri');
  7. /**
  8. * Module exports.
  9. */
  10. module.exports = exports = getUri;
  11. /**
  12. * Supported "protocols".
  13. */
  14. exports.protocols = {
  15. data: require('./data'),
  16. file: require('./file'),
  17. ftp: require('./ftp'),
  18. http: require('./http'),
  19. https: require('./https')
  20. };
  21. /**
  22. * Async function that returns a `stream.Readable` instance to the
  23. * callback function that will output the contents of the given URI.
  24. *
  25. * For caching purposes, you can pass in a `stream` instance from a previous
  26. * `getUri()` call as a `cache: stream` option, and if the destination has
  27. * not changed since the last time the endpoint was retreived then the callback
  28. * will be invoked with an Error object with `code` set to "ENOTMODIFIED" and
  29. * `null` for the "stream" instance argument. In this case, you can skip
  30. * retreiving the file again and continue to use the previous payload.
  31. *
  32. * @param {String} uri URI to retrieve
  33. * @param {Object} opts optional "options" object
  34. * @param {Function} fn callback function
  35. * @api public
  36. */
  37. function getUri (uri, opts, fn) {
  38. debug('getUri(%o)', uri);
  39. if ('function' == typeof opts) {
  40. fn = opts;
  41. opts = null;
  42. }
  43. if ('function' != typeof fn) {
  44. throw new TypeError('a callback function must be provided');
  45. }
  46. if (!uri) return fn(new TypeError('must pass in a URI to "get"'));
  47. var parsed = parse(uri);
  48. var protocol = parsed.protocol;
  49. if (!protocol) return fn(new TypeError('URI does not contain a protocol: ' + uri));
  50. // strip trailing :
  51. protocol = protocol.replace(/\:$/, '');
  52. var getter = exports.protocols[protocol];
  53. if ('function' != typeof getter)
  54. return fn(new TypeError('unsupported protocol "' + protocol + '" specified in URI: ' + uri));
  55. getter(parsed, opts || {}, fn);
  56. }