如何使用js将目录路径list转成tree树结构
例如:
[
'pic0.png'
'src/pic1.png',
'src/pic3.png',
'src/new/pic4.png',
]
1
2
3
4
5
6
2
3
4
5
6
将上面的数据生成下面格式
[
{
name: 'pic0.png',
type: "file",
id: 1
},
{
name: 'src',
type: "directory",
id: 2
children: [
{
name: 'pic1.png',
type: "file",
id: 3
},
{
name: 'pic3.png',
type: "file",
id: 4
},
{
name: 'news',
type: "directory",
id: 5
children: [
{
name: 'pic4.png',
type: "file",
id: 6
}
]
}
]
}
]
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
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
js代码:
const fs = require("fs-extra");
const path = require("path");
const getDirFilePath = (jsonPath) => {
let jsonFiles = [];
function findJsonFile(www) {
let files = fs.readdirSync(www);
files.forEach(function (item, index) {
let fPath = path.join(www, item);
let stat = fs.statSync(fPath);
if (stat.isDirectory() === true) {
findJsonFile(fPath);
}
if (stat.isFile() === true) {
jsonFiles.push(fPath);
}
});
}
findJsonFile(jsonPath);
return jsonFiles;
};
const catalogToTree = (dirPath) => {
let fileArr = getDirFilePath(dirPath);
function buildTree(fileList) {
const tree = {};
fileList.forEach((filePath) => {
filePath = filePath.replace(dirPath, "root");
const pathParts = filePath.split("\\");
let current = tree;
pathParts.forEach((part) => {
if (!current[part]) {
current[part] = {};
}
current = current[part];
});
});
return tree;
}
let result = buildTree(fileArr);
let idIndex = 0;
let loop = (obj, arr) => {
for (const key in obj) {
idIndex = idIndex + 1;
let ob = {
name: key,
id: idIndex,
type: "file",
};
arr.push(ob);
if (obj[key] && Object.keys(obj[key]).length > 0) {
ob.children = [];
ob.type = "directory";
loop(obj[key], ob.children);
}
}
};
let treeArr = [];
loop(result.root, treeArr);
return treeArr;
};
// 调用方法
let dirPath = path.join(__dirname, `../public`);
catalogToTree(dirPath)
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
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
上次更新: 2024/01/30, 00:35:17
- 01
- linux 在没有 sudo 权限下安装 Ollama 框架12-23
- 02
- Express 与 vue3 使用 sse 实现消息推送(长连接)12-20