index.js 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. module.exports = simpleGet
  2. var extend = require('xtend')
  3. var http = require('http')
  4. var https = require('https')
  5. var once = require('once')
  6. var unzipResponse = require('unzip-response') // excluded from browser build
  7. var url = require('url')
  8. function simpleGet (opts, cb) {
  9. opts = typeof opts === 'string' ? { url: opts } : extend(opts)
  10. cb = once(cb)
  11. if (opts.url) parseOptsUrl(opts)
  12. if (opts.headers == null) opts.headers = {}
  13. if (opts.maxRedirects == null) opts.maxRedirects = 10
  14. var body = opts.body
  15. opts.body = undefined
  16. if (body && !opts.method) opts.method = 'POST'
  17. // Request gzip/deflate
  18. var customAcceptEncoding = Object.keys(opts.headers).some(function (h) {
  19. return h.toLowerCase() === 'accept-encoding'
  20. })
  21. if (!customAcceptEncoding) opts.headers['accept-encoding'] = 'gzip, deflate'
  22. // Support http: and https: urls
  23. var protocol = opts.protocol === 'https:' ? https : http
  24. var req = protocol.request(opts, function (res) {
  25. // Follow 3xx redirects
  26. if (res.statusCode >= 300 && res.statusCode < 400 && 'location' in res.headers) {
  27. opts.url = res.headers.location
  28. parseOptsUrl(opts)
  29. res.resume() // Discard response
  30. opts.maxRedirects -= 1
  31. if (opts.maxRedirects > 0) simpleGet(opts, cb)
  32. else cb(new Error('too many redirects'))
  33. return
  34. }
  35. cb(null, typeof unzipResponse === 'function' ? unzipResponse(res) : res)
  36. })
  37. req.on('error', cb)
  38. req.end(body)
  39. return req
  40. }
  41. module.exports.concat = function (opts, cb) {
  42. return simpleGet(opts, function (err, res) {
  43. if (err) return cb(err)
  44. var chunks = []
  45. res.on('data', function (chunk) {
  46. chunks.push(chunk)
  47. })
  48. res.on('end', function () {
  49. cb(null, Buffer.concat(chunks), res)
  50. })
  51. })
  52. }
  53. ;['get', 'post', 'put', 'patch', 'head', 'delete'].forEach(function (method) {
  54. module.exports[method] = function (opts, cb) {
  55. if (typeof opts === 'string') opts = { url: opts }
  56. opts.method = method.toUpperCase()
  57. return simpleGet(opts, cb)
  58. }
  59. })
  60. function parseOptsUrl (opts) {
  61. var loc = url.parse(opts.url)
  62. if (loc.hostname) opts.hostname = loc.hostname
  63. if (loc.port) opts.port = loc.port
  64. if (loc.protocol) opts.protocol = loc.protocol
  65. opts.path = loc.path
  66. delete opts.url
  67. }