44 lines
1.5 KiB
JavaScript
44 lines
1.5 KiB
JavaScript
import { readFile, writeFile } from 'node:fs/promises'
|
||
import { resolve } from 'node:path'
|
||
|
||
const [inputFile, outputFile] = process.argv.slice(2)
|
||
|
||
if (!inputFile || !outputFile) {
|
||
throw new Error('用法:node scripts/generate-native-place-data.mjs <ok_data_level4.csv> <输出文件>')
|
||
}
|
||
|
||
function parseCsvLine(line) {
|
||
const values = []
|
||
let value = ''
|
||
let quoted = false
|
||
|
||
for (let index = 0; index < line.length; index += 1) {
|
||
const character = line[index]
|
||
if (character === '"') {
|
||
if (quoted && line[index + 1] === '"') {
|
||
value += character
|
||
index += 1
|
||
} else {
|
||
quoted = !quoted
|
||
}
|
||
} else if (character === ',' && !quoted) {
|
||
values.push(value)
|
||
value = ''
|
||
} else {
|
||
value += character
|
||
}
|
||
}
|
||
values.push(value)
|
||
return values
|
||
}
|
||
|
||
const csv = await readFile(resolve(inputFile), 'utf8')
|
||
const rows = csv.trim().split(/\r?\n/).slice(1).map((line) => {
|
||
const [id, pid, deep, , , , , name] = parseCsvLine(line)
|
||
return [Number(id), Number(pid), Number(deep), name]
|
||
})
|
||
|
||
const source = `// 由 AreaCity-JsSpider-StatsGov 的 ok_data_level4.csv 生成,数据版本 2025.251231.260403(2026-04-03)。\n// 上游项目采用 MIT License:https://github.com/xiangyuecn/AreaCity-JsSpider-StatsGov\nexport type NativePlaceRow = readonly [id: number, pid: number, deep: number, name: string]\n\nexport const nativePlaceRows: readonly NativePlaceRow[] = ${JSON.stringify(rows)} as const\n`
|
||
|
||
await writeFile(resolve(outputFile), source, 'utf8')
|