down-img.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. const https = require('https');
  2. const fs = require('fs');
  3. const { format } = require('path');
  4. /**
  5. * 下载图片
  6. * @param { object } obj
  7. * @description 遍历对象里值里包含img.alicdn.com认定为图片
  8. */
  9. function downImg(obj) {
  10. if (type(obj) === 'string') {
  11. // 暂定图片都在img.alicdn.com下
  12. if (obj.indexOf('img.alicdn.com') !== -1) {
  13. if (obj.indexOf('//') === 0) {
  14. obj = 'https:' + obj;
  15. }
  16. updataImg(obj);
  17. }
  18. } else if (type(obj) === 'object') {
  19. for (const n in obj) {
  20. downImg(obj[n])
  21. }
  22. } else if (type(obj) === 'array') {
  23. for (let item of obj) {
  24. downImg(item)
  25. }
  26. }
  27. }
  28. // 根据 url 下载图片
  29. function updataImg(url) {
  30. //访问图片
  31. https.get(url, (res) => {
  32. //用来存储图片二进制编码
  33. let imgData = '';
  34. let name = url.replace(/.+\/(.+)$/igm, '$1');
  35. //设置图片编码格式
  36. res.setEncoding("binary");
  37. //检测请求的数据
  38. res.on('data', (chunk) => {
  39. imgData += chunk;
  40. })
  41. //请求完成执行的回调
  42. res.on('end', () => {
  43. // 通过文件流操作保存图片
  44. fs.writeFile(`./output/imgs/${name}`, imgData, 'binary', (error) => {
  45. // if (error) {
  46. // console.log('下载失败');
  47. // } else {
  48. // console.log('下载成功!')
  49. // }
  50. })
  51. })
  52. })
  53. }
  54. // 判断类型
  55. function type(obj) {
  56. var toString = Object.prototype.toString;
  57. var map = {
  58. '[object Boolean]': 'boolean',
  59. '[object Number]': 'number',
  60. '[object String]': 'string',
  61. '[object Function]': 'function',
  62. '[object Array]': 'array',
  63. '[object Date]': 'date',
  64. '[object RegExp]': 'regExp',
  65. '[object Undefined]': 'undefined',
  66. '[object Null]': 'null',
  67. '[object Object]': 'object'
  68. };
  69. return map[toString.call(obj)];
  70. }
  71. exports.downImg = downImg;