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