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.

74 lines
1.8 KiB

4 years ago
  1. var http = require('http');
  2. var https = require('https');
  3. var url = require('url');
  4. var isHttpResource = require('../utils/is-http-resource');
  5. var isHttpsResource = require('../utils/is-https-resource');
  6. var override = require('../utils/override');
  7. var HTTP_PROTOCOL = 'http:';
  8. function loadRemoteResource(uri, inlineRequest, inlineTimeout, callback) {
  9. var proxyProtocol = inlineRequest.protocol || inlineRequest.hostname;
  10. var errorHandled = false;
  11. var requestOptions;
  12. var fetch;
  13. requestOptions = override(
  14. url.parse(uri),
  15. inlineRequest || {}
  16. );
  17. if (inlineRequest.hostname !== undefined) {
  18. // overwrite as we always expect a http proxy currently
  19. requestOptions.protocol = inlineRequest.protocol || HTTP_PROTOCOL;
  20. requestOptions.path = requestOptions.href;
  21. }
  22. fetch = (proxyProtocol && !isHttpsResource(proxyProtocol)) || isHttpResource(uri) ?
  23. http.get :
  24. https.get;
  25. fetch(requestOptions, function (res) {
  26. var chunks = [];
  27. var movedUri;
  28. if (errorHandled) {
  29. return;
  30. }
  31. if (res.statusCode < 200 || res.statusCode > 399) {
  32. return callback(res.statusCode, null);
  33. } else if (res.statusCode > 299) {
  34. movedUri = url.resolve(uri, res.headers.location);
  35. return loadRemoteResource(movedUri, inlineRequest, inlineTimeout, callback);
  36. }
  37. res.on('data', function (chunk) {
  38. chunks.push(chunk.toString());
  39. });
  40. res.on('end', function () {
  41. var body = chunks.join('');
  42. callback(null, body);
  43. });
  44. })
  45. .on('error', function (res) {
  46. if (errorHandled) {
  47. return;
  48. }
  49. errorHandled = true;
  50. callback(res.message, null);
  51. })
  52. .on('timeout', function () {
  53. if (errorHandled) {
  54. return;
  55. }
  56. errorHandled = true;
  57. callback('timeout', null);
  58. })
  59. .setTimeout(inlineTimeout);
  60. }
  61. module.exports = loadRemoteResource;