index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. 'use strict';
  2. const fs = require('fs');
  3. const path = require('path');
  4. const url = require('url');
  5. const caw = require('caw');
  6. const decompress = require('decompress');
  7. const filenamify = require('filenamify');
  8. const getStream = require('get-stream');
  9. const got = require('got');
  10. const mkdirp = require('mkdirp');
  11. const pify = require('pify');
  12. const fsP = pify(fs);
  13. const createPromise = (uri, output, stream, opts) => {
  14. const response = opts.encoding === null ? getStream.buffer(stream) : getStream(stream, opts);
  15. return response.then(data => {
  16. if (!output && opts.extract) {
  17. return decompress(data, opts);
  18. }
  19. if (!output) {
  20. return data;
  21. }
  22. if (opts.extract) {
  23. return decompress(data, path.dirname(output), opts);
  24. }
  25. return pify(mkdirp)(path.dirname(output))
  26. .then(() => fsP.writeFile(output, data))
  27. .then(() => data);
  28. });
  29. };
  30. module.exports = (uri, output, opts) => {
  31. if (typeof output === 'object') {
  32. opts = output;
  33. output = null;
  34. }
  35. opts = Object.assign({
  36. encoding: null,
  37. rejectUnauthorized: process.env.npm_config_strict_ssl !== 'false'
  38. }, opts);
  39. let protocol = url.parse(uri).protocol;
  40. if (protocol) {
  41. protocol = protocol.slice(0, -1);
  42. }
  43. const agent = caw(opts.proxy, {protocol});
  44. const stream = got.stream(uri, Object.assign(opts, {agent}));
  45. const dest = output ? path.join(output, filenamify(path.basename(uri))) : null;
  46. const promise = createPromise(uri, dest, stream, opts);
  47. stream.then = promise.then.bind(promise);
  48. stream.catch = promise.catch.bind(promise);
  49. return stream;
  50. };