|
| 1 | +#!/usr/bin/env node |
| 2 | + |
| 3 | +import fs from 'fs/promises'; |
| 4 | +import path from 'path'; |
| 5 | +import { XMLParser } from 'fast-xml-parser'; |
| 6 | +import { fileURLToPath } from "url"; |
| 7 | + |
| 8 | +const __filename = fileURLToPath(import.meta.url); |
| 9 | +const __dirname = path.dirname(__filename); |
| 10 | + |
| 11 | +type SearchEntry = { |
| 12 | + code: string; |
| 13 | + name: string; |
| 14 | + age: string; |
| 15 | + block: string; |
| 16 | + category: string; |
| 17 | +} |
| 18 | + |
| 19 | +type SearchData = { |
| 20 | + success: boolean; |
| 21 | + data: SearchEntry[]; |
| 22 | +} |
| 23 | + |
| 24 | +async function main() { |
| 25 | + console.log(`INFO: starting at ${new Date().toISOString()}`); |
| 26 | + |
| 27 | + const xmlPath = path.join( __dirname, '..', 'tmp', 'ucd.all.flat.xml' ); |
| 28 | + const jsonPath = path.join( __dirname, '..', 'public', 'ucd.json' ); |
| 29 | + |
| 30 | + try { |
| 31 | + await fs.access(xmlPath); |
| 32 | + } catch (err) { |
| 33 | + console.log(`INFO: XML file does not exist in ${xmlPath}`); |
| 34 | + process.exit(1); |
| 35 | + } |
| 36 | + |
| 37 | + // Read and parse the XML file |
| 38 | + console.log(`INFO: reading XML file from ${xmlPath}`); |
| 39 | + const xmlData = await fs.readFile(xmlPath, 'utf-8'); |
| 40 | + console.log(`INFO: parsing XML data`); |
| 41 | + const parser = new XMLParser({ |
| 42 | + ignoreAttributes: false, |
| 43 | + attributeNamePrefix: '', |
| 44 | + }); |
| 45 | + const jsonObj = parser.parse(xmlData); |
| 46 | + |
| 47 | + const entries: SearchEntry[] = []; |
| 48 | + |
| 49 | + for (const charData of jsonObj.ucd.repertoire.char) { |
| 50 | + entries.push({ |
| 51 | + code: charData.cp, |
| 52 | + name: charData.na || charData.na1, |
| 53 | + age: charData.age, |
| 54 | + block: charData.blk, |
| 55 | + category: charData.gc, |
| 56 | + }); |
| 57 | + } |
| 58 | + |
| 59 | + const output: SearchData = { |
| 60 | + success: true, |
| 61 | + data: entries, |
| 62 | + }; |
| 63 | + |
| 64 | + // Write the JSON data to a file |
| 65 | + console.log(`INFO: writing JSON data to ${jsonPath}`); |
| 66 | + await fs.writeFile(jsonPath, JSON.stringify(output, null, 2), 'utf-8'); |
| 67 | + console.log(`INFO: wrote JSON data to ${jsonPath}`); |
| 68 | +} |
| 69 | + |
| 70 | + |
| 71 | + |
| 72 | +main().then( () => { |
| 73 | + console.log(`INFO: complete at ${new Date().toISOString()}`); |
| 74 | +}); |
0 commit comments