fetch.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. var fs = require('fs');
  2. var tar = require('tar');
  3. var path = require('path');
  4. var zlib = require('zlib');
  5. var request = require('request');
  6. var chalk = require('chalk');
  7. var fetch = module.exports;
  8. var proxy = process.env.http_proxy || process.env.HTTP_PROXY ||
  9. process.env.https_proxy || process.env.HTTPS_PROXY || '';
  10. /**
  11. * Download a single file to a given destination.
  12. *
  13. * @param {String} url
  14. * @param {String} destination
  15. * @param {Function} cb
  16. */
  17. fetch.fetch = function _fetch(url, destination, cb) {
  18. this.mkdir(path.dirname(destination));
  19. var log = this.log('... Fetching %s ...', url);
  20. fetch.request(url)
  21. .on('error', cb)
  22. .on('data', function () {
  23. log.write('.');
  24. })
  25. .pipe(fs.createWriteStream(destination))
  26. .on('error', cb)
  27. .on('close', function () {
  28. log.write('Writing ' + destination + '...');
  29. })
  30. .on('close', cb);
  31. };
  32. /**
  33. * Fetch a tarball and extract it to a given destination.
  34. *
  35. * @param {String} tarball
  36. * @param {String} target
  37. * @param {Function} cb
  38. */
  39. fetch.tarball = function _tarball(tarball, target, cb) {
  40. var now = Date.now();
  41. var log = this.log.write()
  42. .info('... Fetching %s ...', tarball)
  43. .info(chalk.yellow('This might take a few moments'));
  44. var extractOpts = { type: 'Directory', path: target, strip: 1 };
  45. var req = fetch.request.get(tarball).on('error', cb);
  46. req.on('data', function () {
  47. log.write('.');
  48. }).on('end', function () {
  49. log.write().ok('Done in ' + (Date.now() - now) / 1000 + 's.');
  50. });
  51. req
  52. .pipe(zlib.Unzip())
  53. .on('error', function (err) {
  54. console.error('unzip error', err);
  55. cb(err);
  56. })
  57. .pipe(tar.Extract(extractOpts))
  58. .on('entry', function (entry) {
  59. entry.props.uid = entry.uid = 501;
  60. entry.props.gid = entry.gid = 20;
  61. })
  62. .on('error', function (err) {
  63. console.error('untar error', err);
  64. cb(err);
  65. })
  66. .on('close', function () {
  67. log.ok('Done in ' + extractOpts.path).write();
  68. cb();
  69. });
  70. };
  71. fetch.request = request.defaults({ proxy: proxy });