-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.js
77 lines (68 loc) · 1.84 KB
/
utils.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
/*
* Util
* @Author: John Trump
* @Date: 2020-12-11 17:41:00
* @LastEditors: John Trump
* @LastEditTime: 2020-12-11 18:02:56
*/
const fs = require('fs');
const path = require('path');
const { promisify } = require("util");
const dayjs = require("dayjs");
const axios = require("axios").default;
/**
* Merge record, 根据日期去重
* @param {array} older
* @param {array} newer
*/
const mergeRecord = (older, newer) => {
const obj = {};
for (const item of older.concat(newer)) {
obj[item.dateTime] = { ...item };
}
return Object.entries(obj).map(([dateTime, other]) => ({
dateTime,
...other,
}));
};
/** 结果写入json */
const writeToJSON = async (record) => {
const yyyyMM = dayjs(new Date()).format("YYYY-MM");
const fullPath = path.join("raw", `${yyyyMM}.json`);
let records = [];
// if exist, parse json to object
if (await fs.existsSync(fullPath)) {
const context = await promisify(fs.readFile)(fullPath);
records = JSON.parse(context);
}
/* MergeRecord */
records = mergeRecord(records, [{ ...record }]);
// write to file
await promisify(fs.writeFile)(fullPath, JSON.stringify(records, "", 2));
return true;
};
/**
* 获取图片并保存
* @param {string} locate image path, exclude baseUrl
* @param {string} baseUrl baseUrl, default is equal to {URL}
*/
const fetchImage = (locate, baseUrl) => {
return new Promise(async (resolve) => {
let fileName = locate.split("/")[2] || "unknown";
const response = await axios.get(`${baseUrl}${locate}`, {
responseType: "stream",
});
/* remove random stamp */
fileName = fileName.replace(/(\?id=\-?\w+)/gm, "");
response.data
.pipe(fs.createWriteStream(`temp/${fileName}.png`))
.on("finish", () => {
resolve(fileName);
});
});
};
module.exports = {
mergeRecord,
writeToJSON,
fetchImage
};