puning-real-estate/scripts/generateCsv.js
2026-01-22 10:24:47 +08:00

30 lines
1.0 KiB
JavaScript

import fs from 'fs/promises';
/**
* Generates a CSV file from the given data.
* @param {Array<Object>} data - The data to convert to CSV.
* @param {string} filePath - The path to save the CSV file.
*/
async function generateCsv(data, filePath) {
if (data.length === 0) {
console.log(`没有数据可生成 CSV 文件 (${filePath})。`);
return;
}
const headers = Object.keys(data[0]);
const csvRows = [];
csvRows.push(headers.map(header => `"${header}"`).join(','));
for (const record of data) {
const values = headers.map(header => {
const value = record[header];
// Ensure values are properly quoted and internal quotes are escaped
return `"${String(value).replace(new RegExp('"', 'g'), '""')}"`;
});
csvRows.push(values.join(','));
}
const csvContent = csvRows.join('\n');
const BOM = '\uFEFF'; // UTF-8 BOM
await fs.writeFile(filePath, BOM + csvContent, 'utf-8');
console.log(`已生成 ${filePath} 文件。`);
}