import fs from 'fs/promises'; async function jsonToCsv() { try { const jsonFilePath = './data.json'; const csvFilePath = './data.csv'; const data = await fs.readFile(jsonFilePath, 'utf-8'); const records = JSON.parse(data); if (records.length === 0) { console.log('data.json 文件为空,没有数据可转换为 CSV。'); return; } // Extract headers from the first record const headers = Object.keys(records[0]); const csvRows = []; // Add headers as the first row in CSV csvRows.push(headers.map(header => `"${header}"`).join(',')); // Convert each record to a CSV row for (const record of records) { const values = headers.map(header => { const value = record[header]; // Handle potential commas or double quotes within the data by enclosing in double quotes // and escaping existing double quotes. return `"${String(value).replace(new RegExp('"', 'g'), '""')}"`; }); csvRows.push(values.join(',')); } await fs.writeFile(csvFilePath, csvRows.join('\n'), 'utf-8'); console.log(`成功将 data.json 转换为 ${csvFilePath}`); } catch (error) { console.error('转换 JSON 到 CSV 时发生错误:', error.message); } } jsonToCsv();