-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
fileUtil.js
88 lines (85 loc) · 2.56 KB
/
fileUtil.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
86
87
88
/**
* @description 文件操作封装工具类
*/
const fs = require('fs');
const path = require('path');
/**
* @description 删除文件夹及文件夹下所有文件
* Delete folder and all files under folder
* @param {String} dirPath The path to the dir
* @param {Boolean} delCurrDir 是否删除最外层文件夹,如果为false,则保留空文件夹,默认为true
*/
const deleteFolder = module.exports.deleteFolder = function (dirPath, delCurrDir = true) {
if (fs.existsSync(dirPath)) {
try {
// 指定目录下所有文件名称
const lsDir = fs.readdirSync(dirPath);
lsDir.forEach(function (fileName, index) {
const curPath = path.join(dirPath, fileName);
// recurse
if (fs.statSync(curPath).isDirectory()) {
deleteFolder(curPath);
} else {
// delete file
fs.unlinkSync(curPath);
}
});
if (!!delCurrDir && delCurrDir) {
fs.rmdirSync(dirPath);
}
} catch (ex) {
console.error("Delete folder error:" + ex.message);
}
}
}
/**
* Lists files in the supplied directory path
* @param {String} dirPath The path to the dir
* @return {Array} An array that contains all the file paths
*/
const listFiles = module.exports.listFiles = function (dirPath) {
try {
// 指定目录下所有文件名称
const lsDir = fs.readdirSync(dirPath);
const filesArr = [];
for (const fileName of lsDir) {
const pathName = path.join(dirPath, fileName);
if (fs.statSync(pathName).isDirectory()) {
// 三点运算符
filesArr.push(...listFiles(pathName));
} else {
filesArr.push(pathName);
}
}
return filesArr;
} catch (e) {
console.warn("Not Found dirPath Files:" + dirPath);
return null;
}
};
/**
* 获取指定目录下一级目录名称
* @param {String} dirPath The path to the dir
* @return {Array} 指定目录下所有一级目录名称
*/
const listFolder = module.exports.listFolder = function (dirPath) {
try {
// 指定目录下所有文件名称
const lsDir = fs.readdirSync(dirPath);
const foldersArr = [];
for (const dirName of lsDir) {
const pathName = path.join(dirPath, dirName);
if (fs.statSync(pathName).isDirectory()) {
// 三点运算符
// foldersArr.push(...listFolder(pathName));
foldersArr.push(pathName);
} else {
// Skip
}
}
return foldersArr;
} catch (ex) {
console.warn("Not Found dirPath Folders:" + dirPath + "error:" + ex.message);
return null;
}
};