patch-core.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. var url = require('url');
  2. var http = require('http');
  3. var https = require('https');
  4. var semver = require('semver');
  5. var inherits = require('util').inherits;
  6. // we only need to patch the `http.request()` and
  7. // `http.ClientRequest` on older versions of Node.js
  8. if (semver.lt(process.version, '0.11.8')) {
  9. // subclass the native ClientRequest to include the
  10. // passed in `options` object.
  11. http.ClientRequest = (function (_ClientRequest) {
  12. function ClientRequest (options, cb) {
  13. this._options = options;
  14. _ClientRequest.call(this, options, cb);
  15. }
  16. inherits(ClientRequest, _ClientRequest);
  17. return ClientRequest;
  18. })(http.ClientRequest);
  19. // need to re-define the `request()` method, since on node v0.8/v0.10
  20. // the closure-local ClientRequest is used, rather than the monkey
  21. // patched version we have created here.
  22. http.request = (function (request) {
  23. return function (options, cb) {
  24. if (typeof options === 'string') {
  25. options = url.parse(options);
  26. }
  27. if (options.protocol && options.protocol !== 'http:') {
  28. throw new Error('Protocol:' + options.protocol + ' not supported.');
  29. }
  30. return new http.ClientRequest(options, cb);
  31. };
  32. })(http.request);
  33. }
  34. // this currently needs to be applied to all Node.js versions
  35. // (v0.8.x, v0.10.x, v0.12.x), in order to determine if the `req`
  36. // is an HTTP or HTTPS request. There is currently no PR attempting
  37. // to move this property upstream.
  38. https.request = (function (request) {
  39. return function (options, cb) {
  40. if (typeof options === 'string') {
  41. options = url.parse(options);
  42. }
  43. if (null == options.port) options.port = 443;
  44. options.secureEndpoint = true;
  45. return request.call(https, options, cb);
  46. };
  47. })(https.request);