42 lines
1.1 KiB
JavaScript
42 lines
1.1 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]
|
|
})
|
|
|
|
await writeFile(resolve(outputFile), `${JSON.stringify(rows)}\n`, 'utf8')
|