-
Notifications
You must be signed in to change notification settings - Fork 0
/
FileHandler.ts
572 lines (518 loc) · 17 KB
/
FileHandler.ts
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
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
/**
* 文件相关操作
*/
import * as fs from 'fs';
// import fs from 'fs/promises';
import * as path from 'path';
import { homedir } from "os";
import { exec, execSync } from 'child_process';
export class FileHandler {
// public static logFile = () => path.join(Config.configFolder(), 'log.txt')
/**
* 判断文件是否存在
* @param filePath
* @returns
*/
public static fileExists(filePath: string): boolean {
return fs.existsSync(filePath);
}
/**
* 递归创建目录
* @param dirPath 目录路径
*/
public static createDirectory(dirPath: string) {
if (!this.fileExists(dirPath)) {
this.createDirectory(path.dirname(dirPath));
fs.mkdirSync(dirPath);
}
}
/**
* 创建文件
* @param filePath 文件路径
*/
public static async ensureDirectoryExistence(filePath: string, defaultValue: string = '') {
this.createDirectory(path.dirname(filePath));
if (!this.fileExists(filePath)) {
fs.writeFileSync(filePath, defaultValue);
}
}
/**
* 复制文件
* @param source 原文件
* @param target 目标文件
* @returns
*/
public static copyFile(source: string, target: string): Promise<boolean> {
return new Promise<boolean>(async (resolve, reject) => {
try {
this.createDirectory(path.dirname(target));
// 判断文件是否存在 如果存在则备份文件 名称为 *.gmmback
if (this.fileExists(target)) {
console.log(`${target} 文件存在, 进行备份`);
let backFile = target + '.gmmback'
await this.copyFile(target, backFile)
}
fs.copyFileSync(source, target);
resolve(true)
} catch (err) {
reject(false)
}
})
}
/**
* 复制文件夹
* @param srcPath 原文件夹
* @param target 目标文件夹
*/
public static copyFolder(srcPath: string, target: string) {
return new Promise<boolean>((resolve, reject) => {
try {
// 获取源文件夹内所有的文件和子文件夹
const files = fs.readdirSync(srcPath);
// 遍历子文件和子文件夹
files.forEach(async file => {
// 源文件/文件夹的完整路径
const srcFilePath = path.join(srcPath, file);
// 目标文件/文件夹的完整路径
const destFilePath = path.join(target, file);
// 如果是文件夹,则递归调用该文件夹下的所有文件和文件夹
if (fs.statSync(srcFilePath).isDirectory()) {
this.createDirectory(destFilePath);
await this.copyFolder(srcFilePath, destFilePath);
} else {
// 复制文件
await this.copyFile(srcFilePath, destFilePath)
}
});
resolve(true)
} catch (error) {
reject(false)
}
})
}
// 移动文件
public static moveFile(srcPath: string, destPath: string) {
return new Promise<boolean>((resolve, reject) => {
try {
this.createDirectory(path.dirname(destPath));
fs.renameSync(srcPath, destPath)
resolve(true)
} catch (error) {
reject(false)
}
})
}
/**
* 移动文件夹
* @param srcPath 原文件夹
* @param destPath 目标文件夹
* @returns
*/
public static moveFolder(srcPath: string, destPath: string) {
return new Promise<boolean>((resolve, reject) => {
try {
this.getAllFiles(srcPath).forEach(async file => {
let dest = file.replace(srcPath, destPath)
await this.moveFile(file, dest)
})
this.deleteFolder(srcPath)
resolve(true)
} catch (error) {
reject(false)
}
})
}
/**
* 删除文件夹
* @param folderPath 文件夹路径
* @returns
*/
public static deleteFolder(folderPath: string): boolean {
try {
const files = fs.readdirSync(folderPath);
// 删除每个文件和子目录
files.forEach(file => {
const filePath = path.join(folderPath, file);
// 如果是子目录,递归调用自身
if (fs.lstatSync(filePath).isDirectory()) {
this.deleteFolder(filePath);
} else { // 否则直接删除文件
this.deleteFile(filePath);
}
});
// 删除空目录
fs.rmdirSync(folderPath);
return true
} catch (err) {
return false
}
}
/**
* 删除文件
* @param filePath 文件路径
* @returns
*/
public static deleteFile(filePath: string) {
try {
if (this.fileExists(filePath)) {
fs.unlinkSync(filePath);
// 判断是否有备份文件
let backFile = filePath + '.gmmback'
if (this.fileExists(backFile)) {
console.log(`${filePath} 存在备份,进行还原`);
this.renameFile(backFile, filePath)
}
}
return true
} catch (err) {
return false
}
}
/**
* 读取文件 异步
* @param filePath 文件路径
* @param defaultValue 若文件不存在时的创建文件的默认值
* @returns
*/
public static async readFileSync(filePath: string, defaultValue: string = ''): Promise<string> {
await this.ensureDirectoryExistence(filePath, defaultValue)
let data = fs.readFileSync(filePath, 'utf-8')
return data
}
/**
* 读取文件 同步
* @param filePath
* @returns
*/
public static readFile(filePath: string, defaultValue?: string): string {
if (this.fileExists(filePath)) {
let data = fs.readFileSync(filePath, 'utf-8')
return data
} else {
// 不存在则创建文件
this.ensureDirectoryExistence(filePath, defaultValue)
return this.readFile(filePath)
}
}
/**
* 写入文件
* @param filePath 文件路径
* @param data 写入的数据
* @returns
*/
public static writeFile(filePath: string, data: string | Buffer): Promise<boolean> {
return new Promise((resolve, reject) => {
try {
this.createDirectory(path.dirname(filePath));
// 判断文件是否存在
if (!this.fileExists(filePath)) {
fs.writeFileSync(filePath, data);
resolve(true)
return
}
fs.writeFileSync(filePath, data);
resolve(true)
} catch (err) {
reject(err)
}
})
}
/**
* 打开文件夹
* @param folderPath 打开文件夹
*/
public static openFolder(folderPath: string) {
exec(`explorer "${folderPath}"`);
}
/**
* 打开文件
* @param filePath 文件路径
*/
public static openFile(filePath: string) {
console.log(filePath);
exec(`open "${filePath}"`)
}
/**
* 重命名文件
* @param filePath 文件路径
* @param newName 目标名称
* @returns
*/
public static renameFile(filePath: string, newName: string): Promise<void> {
return new Promise((resolve, reject) => {
try {
fs.renameSync(filePath, newName)
resolve()
} catch (error) {
reject(error)
}
})
}
/**
* 获取文件大小
* @param filePath 文件路径
*/
public static async getFileSize(filePath: string) {
const fileStat = await fs.promises.stat(filePath);
if (fileStat.isFile()) {
return fileStat.size;
} else if (fileStat.isDirectory()) {
let size = 0;
const files = await fs.promises.readdir(filePath);
for (let i = 0; i < files.length; i++) {
size += await this.getFileSize(path.join(filePath, files[i]));
}
return size;
}
return 0
}
/**
* 获取文件夹下的所有文件
* @param folder
*/
public static getAllFiles(folder: string) {
let res: string[] = [];
const files = fs.readdirSync(folder);
files.forEach((file) => {
const filePath = path.join(folder, file);
const stat = fs.statSync(filePath);
if (stat.isFile()) {
res.push(filePath);
} else if (stat.isDirectory()) {
res = res.concat(this.getAllFiles(filePath));
}
});
return res;
}
/**
* 运行程序
* @param exe 程序路径
*/
public static runExe(exe: string) {
let { root, dir: folder, base: name } = path.parse(exe)
// 去除 root 中的 \
root = root.replace(/\\/g, '')
let cmd = `${root} && cd "${folder}" && "${name}" `;
console.log(cmd);
exec(cmd)
}
/**
* 创建软连接
* @param folderPath 文件夹路径
* @param destPath 软链接路径
* @returns
*/
public static createLink(folderPath: string, destPath: string, backup: boolean = false) {
// symlinkSync
try {
if (backup) {
if (this.fileExists(destPath)) {
let backFile = destPath + '_back'
this.renameFile(destPath, backFile)
}
}
this.createDirectory(path.join(destPath, '..'))
fs.symlinkSync(folderPath, destPath, 'junction');
return true
} catch (error) {
return false
}
}
// 判断路径是否是软链
public static isSymlink(path: string): Promise<boolean> {
return new Promise((resolve, reject) => {
fs.lstat(path, (err, stats) => {
if (err) {
reject(err);
} else {
resolve(stats.isSymbolicLink());
}
});
});
}
/**
* 移除软连接
* @param linkPath 软连接路径
* @returns
*/
public static removeLink(linkPath: string, backup: boolean = false) {
try {
// this.createDirectory(path.join(linkPath, '..'))
fs.unlinkSync(linkPath)
if (backup) {
// 判断是否有备份 有则还原
let backFile = linkPath + '_back'
if (this.fileExists(backFile)) {
this.renameFile(backFile, linkPath)
}
}
return true
} catch (error) {
return false
}
}
/**
* 将路径转换为数组
* @param filePath 路径
* @returns
*/
public static pathToArray(filePath: string) {
// 将 / 替换为 path.sep
// filePath = filePath.replace(/\//g, path.sep)
// 通过 path.sep 或 / 分割路径
return filePath.split(/\/|\\/)
}
/**
* 获取文件夹中的文件列表
* @param folderPath 路径
* @returns
*/
public static getFolderFiles(folderPath: string, includepath?: boolean, child: boolean = false) {
return FileHandler.getAllFilesInFolder(folderPath, includepath, child)
}
/**
* 从指定路径中获取指定文件夹后的目录
* @param folderPath 路径
* @param folderName 查找的文件夹名
* @param include 是否包含查找的文件夹
* @returns
*/
public static getFolderFromPath(folderPath: string, folderName: string, include = false): string | null {
let folders = this.pathToArray(folderPath)
// 不区分大小写
let index = folders.findIndex(item => item.toLowerCase() == folderName.toLowerCase())
if (index === -1) {
return null
}
if (include) {
return folders.slice(index).join(path.sep)
} else {
return folders.slice(index + 1).join(path.sep)
}
}
// 获取程序目录下的 resources 目录
public static getResourcesPath() {
return path.join(process.cwd(), 'resources')
}
/**
* 获取我的文档路径
* @returns
*/
public static getMyDocuments() {
try {
// 从注册表 获取 我的文档位置
const regQueryCommand = 'reg query "HKEY_CURRENT_USER\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Shell Folders" /v Personal';
const output = execSync(regQueryCommand, { encoding: 'utf8' }).toString();
const matches = output.match(/Personal\s+REG_SZ\s+(.*)/i);
if (matches && matches[1]) {
let folder = matches[1];
// 判断文件夹是否存在
if (this.fileExists(folder)) {
return folder
} else {
return path.join(homedir(), 'Documents')
}
} else {
return path.join(homedir(), 'Documents')
}
} catch (error) {
return path.join(homedir(), 'Documents')
}
}
/**
* 获取公共父文件夹
* @param paths 文件列表
* @returns
*/
public static getCommonParentFolder(paths: string[]): string {
/// AI 给的写法 虽然看不懂 但感觉很酷
const dirs = paths.map((p) => p.split(path.sep));
if (dirs.some((d) => d.length === 0)) return "";
for (let i = 0; i < dirs[0].length; i++) {
const current = dirs[0][i];
if (dirs.some((d) => d[i] !== current)) {
return dirs[0].slice(0, i).join(path.sep);
}
}
return dirs[0].join(path.sep);
}
/**
* 获取路径下所有的文件
* @param folderPat 路径
* @param includepath 是否包含路径
* @param subdirectory 是否包含子文件夹
* @param getFolderPath 是否获取文件夹路径
* @returns
*/
public static getAllFilesInFolder(folderPath: string, includepath: boolean = false, subdirectory: boolean = false, getFolder = false) {
let res: string[] = [];
const files = fs.readdirSync(folderPath);
files.forEach((file) => {
const filePath = path.join(folderPath, file);
const stat = fs.statSync(filePath);
if (stat.isFile()) {
if (includepath) {
res.push(filePath);
} else {
res.push(file);
}
} else if (stat.isDirectory()) {
if (getFolder) {
res.push(filePath);
}
if (subdirectory) {
res = res.concat(this.getAllFilesInFolder(filePath, includepath, subdirectory, getFolder));
}
}
});
return res;
}
/**
* 获取路径下所有文件夹
* @param folderPath 路径
* @param subdirectory 是否递归获取子目录
* @returns
*/
public static getAllFolderInFolder(folderPath: string, subdirectory: boolean = false) {
let res: string[] = [];
const files = fs.readdirSync(folderPath);
files.forEach((file) => {
const filePath = path.join(folderPath, file);
const stat = fs.statSync(filePath);
if (stat.isDirectory()) {
res.push(filePath);
if (subdirectory) {
const subFolders = this.getAllFolderInFolder(filePath, true);
res = res.concat(subFolders);
}
}
});
return res;
}
// 判断程序是否已经启动
public static async existsSync(name: string) {
return new Promise<boolean>((resolve, reject) => {
try {
let cmd = `tasklist | findstr ${path.basename(name)}`
exec(cmd, (err, stdout, stderr) => {
// console.log(stdout);
if (stdout != '') {
resolve(true)
} else {
resolve(false)
}
});
} catch (error) {
reject(error)
}
})
}
/**
* 判断是否是文件夹
* @param path 路径
* @returns
*/
public static isDir(path: string) {
return fs.statSync(path).isDirectory()
}
}