UNPKG

@opengis/fastify-table

Version:

core-plugins

41 lines (40 loc) 2.1 kB
import path from "node:path"; import { mkdir, readFile, writeFile } from "node:fs/promises"; export default async function convertJSONToCSV({ filePath, send = () => { }, delimiter = ";", colmodel = [], columnList = [], }) { const titles = colmodel .filter((el) => columnList.includes(el.name)) .reduce((acc, curr) => Object.assign(acc, { [curr.name]: curr.title || curr.ua }), {}); const rows = JSON.parse((await readFile(filePath, "utf8")) || "{}"); const orderedRows = rows.reduce((acc, curr) => { const row = colmodel .filter((el) => columnList.includes(el.name)) .map((el) => curr[el.name]); acc.push(row); return acc; }, []); const values = orderedRows.map((row) => Object.values(row).map((el) => { if (Array.isArray(el) && el?.[0] && typeof el?.[0] === "object") { return `${JSON.stringify(el)};`; } if (Array.isArray(el) && el.length && typeof el?.[0] !== "object") { return `${el.join(",")};`; } if (typeof el === "object") { return Object.keys(el || {}).length ? `${JSON.stringify(el)};` : ";"; } return `${el || ""};`; })); values.unshift(colmodel .filter((el) => columnList.includes(el.name)) .map((el) => `${titles[el.name] || el.name};`)); send("Конвертація успішно завершена. Формування файлу..."); await mkdir(path.dirname(filePath), { recursive: true }); await writeFile(filePath.replace(".json", ".csv"), `\ufeff${values .join("\n") .replace(/;,/g, delimiter) .replace(/null/g, "") .replace(/undefined/g, "")}`, "utf8"); // send('Файл успішно сформовано. Оновіть сторінку або натисніть кнопку ще раз для завантаження. ', 1); // return { message: 'Файл успішно сформовано. Натистіть кнопку ще раз для завантаження даних', status: 200 }; return null; }