123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384 |
- const https = require('https');
- const fs = require('fs');
- const { format } = require('path');
- /**
- * 下载图片
- * @param { object } obj
- * @description 遍历对象里值里包含img.alicdn.com认定为图片
- */
- function downImg(obj) {
- if (type(obj) === 'string') {
- // 暂定图片都在img.alicdn.com下
- if (obj.indexOf('img.alicdn.com') !== -1) {
- if (obj.indexOf('//') === 0) {
- obj = 'https:' + obj;
- }
- updataImg(obj);
- }
- } else if (type(obj) === 'object') {
- for (const n in obj) {
- downImg(obj[n])
- }
- } else if (type(obj) === 'array') {
- for (let item of obj) {
- downImg(item)
- }
- }
- }
- // 根据 url 下载图片
- function updataImg(url) {
- //访问图片
- https.get(url, (res) => {
- //用来存储图片二进制编码
- let imgData = '';
- let name = url.replace(/.+\/(.+)$/igm, '$1');
- //设置图片编码格式
- res.setEncoding("binary");
- //检测请求的数据
- res.on('data', (chunk) => {
- imgData += chunk;
- })
- //请求完成执行的回调
- res.on('end', () => {
- // 通过文件流操作保存图片
- fs.writeFile(`./output/imgs/${name}`, imgData, 'binary', (error) => {
- // if (error) {
- // console.log('下载失败');
- // } else {
- // console.log('下载成功!')
- // }
- })
- })
- })
- }
- // 判断类型
- function type(obj) {
- var toString = Object.prototype.toString;
- var map = {
- '[object Boolean]': 'boolean',
- '[object Number]': 'number',
- '[object String]': 'string',
- '[object Function]': 'function',
- '[object Array]': 'array',
- '[object Date]': 'date',
- '[object RegExp]': 'regExp',
- '[object Undefined]': 'undefined',
- '[object Null]': 'null',
- '[object Object]': 'object'
- };
- return map[toString.call(obj)];
- }
- exports.downImg = downImg;
|