返回 AiToEarn
file.util.ts
根目录 / project / aitoearn-electron / server / src / util / file.util.ts
1 import path from 'node:path';
2 import * as fs from 'node:fs';
3
4 enum Type {
5 IMAGE = '图片',
6 TXT = '文档',
7 MUSIC = '音乐',
8 VIDEO = '视频',
9 OTHER = '其他',
10 }
11
12 export function getFileType(extName: string) {
13 const documents = 'txt doc pdf ppt pps xlsx xls docx';
14 const music = 'mp3 wav wma mpa ram ra aac aif m4a';
15 const video = 'avi mpg mpe mpeg asf wmv mov qt rm mp4 flv m4v webm ogv ogg';
16 const image =
17 'bmp dib pcp dif wmf gif jpg tif eps psd cdr iff tga pcd mpt png jpeg';
18 if (image.includes(extName)) return Type.IMAGE;
19
20 if (documents.includes(extName)) return Type.TXT;
21
22 if (music.includes(extName)) return Type.MUSIC;
23
24 if (video.includes(extName)) return Type.VIDEO;
25
26 return Type.OTHER;
27 }
28
29 export function getName(fileName: string) {
30 if (fileName.includes('.')) return fileName.split('.')[0];
31
32 return fileName;
33 }
34
35 export function getExtname(fileName: string) {
36 return path.extname(fileName).replace('.', '');
37 }
38
39 export function getSize(bytes: number, decimals = 2) {
40 if (bytes === 0) return '0 Bytes';
41
42 const k = 1024;
43 const dm = decimals < 0 ? 0 : decimals;
44 const sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
45
46 const i = Math.floor(Math.log(bytes) / Math.log(k));
47
48 return `${Number.parseFloat((bytes / k ** i).toFixed(dm))} ${sizes[i]}`;
49 }
50
51 /**
52 * nodejs存储文件到本地
53 * @param base64String
54 * @param path
55 * @param fileName
56 * @returns
57 */
58 export function saveFile(base64String: string, path: string, fileName: string) {
59 // 文件不存在则创建文件
60 if (!fs.existsSync(path)) {
61 fs.mkdirSync(path, { recursive: true });
62 }
63
64 return new Promise((resolve, reject) => {
65 fs.writeFile(path + fileName, base64String, 'base64', (err) => {
66 if (err) {
67 reject(err);
68 } else {
69 resolve(true);
70 }
71 });
72 });
73 }
74
74 lines TYPESCRIPT