乐闻世界logo
搜索文章和话题

How to export csv using nodejs

1个答案

1

In Node.js, you can use various methods to export CSV files. Here is a basic approach that uses the fs module to write files and manually creates a CSV-formatted string. This approach does not rely on any external libraries.

javascript
const fs = require('fs'); const path = require('path'); // Sample data const data = [ { id: 1, name: 'Alice', age: 25 }, { id: 2, name: 'Bob', age: 22 }, { id: 3, name: 'Charlie', age: 23 } ]; // Convert array of objects to CSV string function convertToCSV(arr) { // Get headers (field names) const csvColumns = Object.keys(arr[0]).join(','); // Get each row data const csvRows = arr.map(row => Object.values(row).join(',') ); // Combine headers and rows, separated by newline characters return [csvColumns].concat(csvRows).join('\r\n'); } // Generate CSV string const csvData = convertToCSV(data); // CSV file path const filePath = path.join(__dirname, 'output.csv'); // Write to CSV file fs.writeFile(filePath, csvData, (err) => { if (err) { console.error('Error writing CSV file:', err); } else { console.log('CSV file has been successfully exported'); } });

If your data contains commas, newline characters, or other special characters, you may need to perform more complex escaping for each value. For this purpose, you can use existing libraries such as csv-writer or fast-csv. Here is an example of exporting CSV using the csv-writer library:

First, you need to install the csv-writer library:

bash
npm install csv-writer

Then, you can use it as follows to export CSV files:

javascript
const createCsvWriter = require('csv-writer').createObjectCsvWriter; // Path and header configuration for CSV file const csvWriter = createCsvWriter({ path: 'output.csv', header: [ { id: 'id', title: 'ID' }, { id: 'name', title: 'NAME' }, { id: 'age', title: 'AGE' } ] }); // Sample data const data = [ { id: 1, name: 'Alice', age: 25 }, { id: 2, name: 'Bob', age: 22 }, { id: 3, name: 'Charlie', age: 23 } ]; // Write to CSV file csvWriter.writeRecords(data) .then(() => { console.log('CSV file has been successfully exported'); }) .catch(err => { console.error('Error writing CSV file:', err); });

Using such libraries can simplify the generation and escaping of CSV data, while also making the code easier to maintain. In actual production environments, it is generally recommended to use these libraries because they are more robust and can handle more edge cases.

2024年6月29日 12:07 回复

你的答案