2026-02-27 12:24:51 +08:00
|
|
|
|
import { parse } from 'csv-parse/browser/esm/sync';
|
|
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 全局缓存已加载的 CSV 内容
|
|
|
|
|
|
*/
|
2026-02-27 12:38:09 +08:00
|
|
|
|
const csvCache = new Map<string, Record<string, string>[]>();
|
2026-02-27 12:24:51 +08:00
|
|
|
|
|
|
|
|
|
|
/**
|
|
|
|
|
|
* 加载 CSV 文件
|
2026-02-27 12:38:09 +08:00
|
|
|
|
* @template T 返回数据的类型,默认为 Record<string, string>
|
2026-02-27 12:24:51 +08:00
|
|
|
|
*/
|
2026-02-27 12:38:09 +08:00
|
|
|
|
export async function loadCSV<T = Record<string, string>>(path: string): Promise<T[]> {
|
2026-02-27 12:24:51 +08:00
|
|
|
|
if (csvCache.has(path)) {
|
2026-02-27 12:38:09 +08:00
|
|
|
|
return csvCache.get(path)! as T[];
|
2026-02-27 12:24:51 +08:00
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
const response = await fetch(path);
|
|
|
|
|
|
const content = await response.text();
|
|
|
|
|
|
const records = parse(content, {
|
|
|
|
|
|
columns: true,
|
|
|
|
|
|
comment: '#',
|
|
|
|
|
|
trim: true,
|
|
|
|
|
|
skipEmptyLines: true
|
|
|
|
|
|
});
|
|
|
|
|
|
|
2026-02-27 12:38:09 +08:00
|
|
|
|
const result = records as Record<string, string>[];
|
2026-02-27 12:24:51 +08:00
|
|
|
|
csvCache.set(path, result);
|
2026-02-27 12:38:09 +08:00
|
|
|
|
return result as T[];
|
2026-02-27 12:24:51 +08:00
|
|
|
|
}
|