import fs from 'node:fs'; import color from 'chalk'; const data = fs.readFileSync('data/products.csv', 'utf-8'); const productAr = data.split('\n').map((row) => row.replace('\n', '')); const headerAr = productAr.shift().split(/\s*,\s*/); console.log(productAr); // console.log(headerAr); // console.log('======='); // console.log(productAr); const convertCsvToJson = (products, headerAr) => { let jsonStr = '[\n'; products.forEach((row, idxRow) => { jsonStr += ' {\n'; row .trim() .split(',') .forEach((elem, idxElem, ar) => { if (ar.length === idxElem + 1) { if (isNaN(elem)) { jsonStr += ` "${headerAr[idxElem]}": "${elem}"\n`; } else { jsonStr += ` "${headerAr[idxElem]}": ${Number(elem)}\n`; } } else { if (isNaN(elem)) { jsonStr += ` "${headerAr[idxElem]}": "${elem}",\n`; } else { jsonStr += ` "${headerAr[idxElem]}": ${Number(elem)},\n`; } } }); if (products.length === idxRow + 1) { jsonStr += ` }\n`; } else { jsonStr += ` },\n`; } }); jsonStr += ']'; console.log(color.yellow(`${jsonStr}`)); fs.writeFile('products.json', jsonStr, 'utf-8', (err) => { if (err) { console.log(err); } else { console.log(color.green('file created!')); } }); }; convertCsvToJson(productAr, headerAr);