-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
75 lines (65 loc) · 2.07 KB
/
index.js
File metadata and controls
75 lines (65 loc) · 2.07 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
const fs = require("fs");
const https = require("https");
const path = require("path");
const { parse } = require("csv-parse/sync");
const { v7: uuidv7 } = require("uuid");
const CSV_FILE = "cities.csv";
const SQL_FILE = "cities.sql";
const CSV_URL =
"https://www.istat.it/storage/codici-unita-amministrative/Elenco-comuni-italiani.csv";
// Helper to download a file
function downloadFile(url, dest) {
return new Promise((resolve, reject) => {
const file = fs.createWriteStream(dest);
https
.get(url, (response) => {
if (response.statusCode !== 200) {
reject(new Error(`Failed to get '${url}' (${response.statusCode})`));
return;
}
response.pipe(file);
file.on("finish", () => {
file.close(resolve);
});
})
.on("error", (err) => {
fs.unlink(dest, () => reject(err));
});
});
}
async function main() {
// Download CSV if not exists
if (!fs.existsSync(CSV_FILE)) {
console.log(`Downloading ${CSV_FILE}...`);
await downloadFile(CSV_URL, CSV_FILE);
console.log("Download completed.");
}
// Read CSV (latin1 encoding)
const csvContent = fs.readFileSync(CSV_FILE, { encoding: "latin1" });
// Parse CSV
const records = parse(csvContent, {
delimiter: ";",
skip_empty_lines: true,
});
// Remove header
records.shift();
// Prepare SQL
const values = [];
for (const row of records) {
// Defensive: skip rows that are too short
if (row.length < 12) continue;
const id = uuidv7();
const city = row[6].replace(/'/g, "''");
const province = row[11].replace(/'/g, "''");
const region = row[10].replace(/'/g, "''");
values.push(`('${id}', '${city}', '${province}', '${region}')`);
}
const sqlHeader = "INSERT INTO cities (id, city, province, region) VALUES\n";
const sqlBody = values.join(",\n") + ";\n";
fs.writeFileSync(SQL_FILE, sqlHeader + sqlBody, { encoding: "utf-8" });
console.log(`Created ${SQL_FILE} with ${values.length} records.`);
}
main().catch((err) => {
console.error("Error:", err);
process.exit(1);
});