-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathutils.js
85 lines (73 loc) · 2.49 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
78
79
80
81
82
83
84
85
const { app } = require('electron');
const axios = require('axios');
const fs = require('fs');
const path = require('path');
const os = require('os');
// 获取本机 IP 地址
function getIPAddress() {
const interfaces = os.networkInterfaces();
for (let dev in interfaces) {
for (let details of interfaces[dev]) {
if (details.family === 'IPv4' && !details.internal) {
if(details.address.includes('192.168')){
return details.address;
}
ip = details.address
}
}
}
return ip
}
function rmFolder(folderPath) {
if (!fs.existsSync(folderPath)) {
fs.mkdirSync(folderPath, { recursive: true });
}
// 获取文件夹中的所有内容
const files = fs.readdirSync(folderPath);
// 遍历每个文件/子文件夹
files.forEach(file => {
const currentPath = path.join(folderPath, file);
// 获取文件/目录的状态
const stats = fs.statSync(currentPath);
if (stats.isDirectory()) {
// 如果是目录,递归删除其中的文件
clearFolderContents(currentPath);
// 删除空目录
fs.rmdirSync(currentPath);
} else {
// 如果是文件,删除文件
fs.unlinkSync(currentPath);
}
});
}
async function downloadFile(url){
const savePath = path.join(app.getPath('userData'), 'downloads');
// fs.rmdirSync(savePath);
rmFolder(savePath)
const response = await axios({method: 'get', url, responseType: 'arraybuffer'})
const disposition = response.headers['content-disposition'];
let fileName = 'default-file'; // 默认文件名
// 解析 Content-Disposition 获取文件名
if (disposition && disposition.indexOf('attachment') !== -1) {
try {
// 尝试解析文件名,并解码
const fileNameMatch = disposition.match(/filename\*?=UTF-8''(.+)/);
if (fileNameMatch && fileNameMatch[1]) {
// 解码文件名,URL 解码
fileName = decodeURIComponent(fileNameMatch[1]);
}
} catch (err) {
console.error('解码文件名时发生错误:', err);
fileName = 'default-file'; // 出现错误时使用默认文件名
}
}
// 文件保存路径
const saveFilePath = path.join(savePath, fileName);
fs.writeFileSync(saveFilePath, Buffer.from(response.data))
return saveFilePath
}
module.exports = {
getIPAddress,
rmFolder,
downloadFile
}