40 lines
1.2 KiB
JavaScript
40 lines
1.2 KiB
JavaScript
/* CSV importer:
|
|
- Reads ./data/products.csv (columns: id,title,description,price,image,supplier_sku)
|
|
- Normalizes and writes ./data/products.json
|
|
*/
|
|
const fs = require('fs');
|
|
const path = require('path');
|
|
const { parse: parseCsv } = require('csv-parse/sync');
|
|
|
|
const inPath = path.join(__dirname, '../data/products.csv');
|
|
const outPath = path.join(__dirname, '../data/products.json');
|
|
|
|
if (!fs.existsSync(inPath)) {
|
|
console.error('No products.csv found in data/. Create data/products.csv first.');
|
|
process.exit(1);
|
|
}
|
|
|
|
const raw = fs.readFileSync(inPath, 'utf8');
|
|
const rows = parseCsv(raw, {
|
|
columns: true,
|
|
skip_empty_lines: true,
|
|
trim: true
|
|
});
|
|
|
|
const toPrice = (value) => {
|
|
const parsed = Number.parseFloat(String(value ?? '').trim());
|
|
return Number.isFinite(parsed) ? parsed : 0;
|
|
};
|
|
|
|
const products = rows.map(r => ({
|
|
id: r.id || r.supplier_sku || `prod-${Math.random().toString(36).slice(2,9)}`,
|
|
title: r.title || 'Untitled',
|
|
description: r.description || '',
|
|
price: toPrice(r.price),
|
|
image: r.image || 'https://via.placeholder.com/400x300?text=Product',
|
|
supplier_sku: r.supplier_sku || ''
|
|
}));
|
|
|
|
fs.writeFileSync(outPath, JSON.stringify(products, null, 2));
|
|
console.log(`Imported ${products.length} products -> data/products.json`);
|