csv-store.ts
4.34 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
112
/** CSV 读写与防覆盖路径校验;输出为 UTF-8 BOM、CRLF 行尾。 */
import crypto from 'node:crypto';
import fs from 'node:fs';
import path from 'node:path';
import process from 'node:process';
import { parse as parseCsv } from 'csv-parse/sync';
import { stringify as stringifyCsv } from 'csv-stringify/sync';
import { UserError } from './errors.ts';
import { COORDINATE_COLUMNS } from './targets.ts';
const BOM = '';
/** UTF-8 / UTF-8 BOM CSV:表头无重名,每条记录列数与表头一致。清单这类辅助文件用这个。 */
export function readTable(file: string, limit: number | null): { header: string[]; rows: string[][] } {
const content = fs.readFileSync(file, 'utf8');
const records = parseCsv(content, {
bom: true,
skip_empty_lines: false,
relax_quotes: false,
relax_column_count: true,
trim: false,
}) as string[][];
const header = records.shift() ?? [];
if (header.length === 0 || new Set(header).size !== header.length) {
throw new UserError('CSV 表头为空或含重名列');
}
// 表尾整行空白与 Excel 同口径:不产生记录,也不算列数错误。
// 中间的空白行仍按错误处理,免得把误粘贴的空行悄悄吞掉。
while (records.length > 0 && records[records.length - 1].every((cell) => cell === '')) {
records.pop();
}
const rows = limit === null ? records : records.slice(0, limit);
rows.forEach((row, position) => {
if (row.length !== header.length) {
throw new UserError(`第 ${position + 2} 条 CSV 记录列数与表头不一致`);
}
});
return { header, rows };
}
/** 数据源用的 CSV:在通用校验之上再要求经纬度列。 */
export function readCsv(file: string, limit: number | null): { header: string[]; rows: string[][] } {
const table = readTable(file, limit);
if (COORDINATE_COLUMNS.some((name) => !table.header.includes(name))) {
throw new UserError('CSV 必须包含经度、纬度列');
}
return table;
}
function pathKeys(file: string): string[] {
const resolved = path.resolve(file);
const keys = [process.platform === 'win32' ? resolved.toLowerCase() : resolved];
try {
const stat = fs.statSync(resolved);
keys.push(`${stat.dev}:${stat.ino}`);
} catch {
// 文件尚不存在(SQLite sidecar 常见):只比较规范化路径。
}
return keys;
}
/** 输入、输出、缓存与日志必须互不相同,禁止覆盖源文件。 */
export function validatePaths(source: string, output: string, cache: string,
tempDir: string): string {
const log = logPathFor(output, tempDir);
const names = [source, output, cache, log,
...['-journal', '-wal', '-shm'].map((suffix) => `${cache}${suffix}`)];
const keys = names.map(pathKeys);
for (let i = 0; i < keys.length; i += 1) {
for (let j = i + 1; j < keys.length; j += 1) {
if (keys[i].some((key) => keys[j].includes(key))) {
throw new UserError('输入、输出、缓存及日志路径必须不同,禁止覆盖源文件');
}
}
}
return log;
}
/**
* 处理日志落在临时目录:文件名跟着输出走,便于对上是哪一次运行。
* 输出目录只放正式交付的表格;日志、清单这类过程文件一律进 .temp。
*/
export function logPathFor(output: string, tempDir: string): string {
return path.join(tempDir, `${path.basename(output, path.extname(output))}.处理日志.csv`);
}
/** 先写同目录临时文件并 fsync,再原子替换,避免中断留下半份文件。 */
export function atomicWrite(file: string, body: string | Uint8Array): void {
const target = path.resolve(file);
const directory = path.dirname(target);
fs.mkdirSync(directory, { recursive: true });
const temporary = path.join(directory,
`${path.basename(target)}.${crypto.randomBytes(6).toString('hex')}.tmp`);
try {
const handle = fs.openSync(temporary, 'w');
try {
fs.writeFileSync(handle, body, 'utf8');
fs.fsyncSync(handle);
} finally {
fs.closeSync(handle);
}
fs.renameSync(temporary, target);
} finally {
if (fs.existsSync(temporary)) fs.unlinkSync(temporary);
}
}
/** UTF-8 BOM + CRLF 行尾的 CSV 输出。 */
export function atomicCsv(file: string, header: readonly string[], rows: readonly string[][]): void {
atomicWrite(file, BOM + stringifyCsv([header as string[], ...rows.map((row) => row as string[])],
{ record_delimiter: '\r\n' }));
}