load-remote-resource.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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;