Repository navigation
Expand file tree
/
Copy pathload_chunked_json.js
More file actions
112 lines (98 loc) · 3.43 KB
/
Copy pathload_chunked_json.js
File metadata and controls
112 lines (98 loc) · 3.43 KB
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
/**
* 分块JSON文件加载器
* 用于加载被分割成多个小块的JSON文件
*/
class ChunkedJSONLoader {
constructor(basePath = '') {
this.basePath = basePath;
this.cache = new Map();
}
/**
* 加载分块的JSON文件
* @param {string} indexFile - 索引文件路径(例如:graph_index_chunks/graph_index_index.json)
* @returns {Promise<Object>} 合并后的完整数据
*/
async loadChunkedJSON(indexFile) {
// 检查缓存
if (this.cache.has(indexFile)) {
return this.cache.get(indexFile);
}
try {
// 加载索引文件
const indexResponse = await fetch(this.basePath + indexFile);
if (!indexResponse.ok) {
throw new Error(`无法加载索引文件: ${indexFile}`);
}
const index = await indexResponse.json();
// 并行加载所有块
const chunkPromises = index.chunk_files.map(chunk => {
const chunkPath = indexFile.replace('_index.json', '') + '/' + chunk.filename;
return fetch(this.basePath + chunkPath)
.then(response => {
if (!response.ok) {
throw new Error(`无法加载块文件: ${chunkPath}`);
}
return response.json();
});
});
const chunks = await Promise.all(chunkPromises);
// 合并数据
let mergedData;
if (index.chunk_files[0].keys) {
// 字典类型:按键合并
mergedData = {};
chunks.forEach((chunk, index) => {
Object.assign(mergedData, chunk);
});
} else {
// 列表类型:按顺序合并
mergedData = [];
chunks.forEach(chunk => {
mergedData.push(...chunk);
});
}
// 缓存结果
this.cache.set(indexFile, mergedData);
return mergedData;
} catch (error) {
console.error('加载分块JSON失败:', error);
throw error;
}
}
/**
* 智能加载JSON文件(自动检测是否需要分块加载)
* @param {string} filePath - JSON文件路径
* @returns {Promise<Object>} JSON数据
*/
async loadJSON(filePath) {
// 首先尝试直接加载
try {
const response = await fetch(this.basePath + filePath);
if (response.ok) {
return await response.json();
}
} catch (error) {
// 如果直接加载失败,尝试分块加载
console.log(`直接加载失败,尝试分块加载: ${filePath}`);
}
// 尝试分块加载
const baseName = filePath.replace('.json', '');
const indexFile = `${baseName}_chunks/${baseName}_index.json`;
try {
return await this.loadChunkedJSON(indexFile);
} catch (error) {
console.error(`无法加载文件(直接和分块都失败): ${filePath}`, error);
throw error;
}
}
/**
* 清除缓存
*/
clearCache() {
this.cache.clear();
}
}
// 导出(如果使用模块系统)
if (typeof module !== 'undefined' && module.exports) {
module.exports = ChunkedJSONLoader;
}