DynamicDataConverter is a versatile tool for converting data between various formats. It supports dynamic format handling and allows for easy extension to new formats and conversions.
- Dynamic Format Handling: Supports conversion between various data formats dynamically.
- Custom Format Registration: Register and use custom formats and converters.
- File Conversion: Convert data files between formats.
- Easy to Use: Simple methods to handle data and files.
No installation is required for this code as it is self-contained and can be added directly to your project. Ensure you have the following packages:
npm install json2csv csv-parse
- Create a DynamicDataConverter Instance
const converter = new DynamicDataConverter();
- Convert Data Between Formats
const jsonArray = [
{ id: 1, name: 'John Doe', email: 'john.doe@example.com' },
{ id: 2, name: 'Jane Doe', email: 'jane.doe@example.com' }
];
// Convert JSON to CSV
const csvData = converter.convert(jsonArray, 'json', 'csv');
console.log('CSV Data:\n', csvData);
// Convert CSV to JSON
const csvString = `id,name,email\n1,John Doe,john.doe@example.com\n2,Jane Doe,jane.doe@example.com`;
const jsonData = converter.convert(csvString, 'csv', 'json');
console.log('JSON Data:\n', jsonData);
- Save to and Read from Files
Save Data to a File
Read Data from a File
converter.saveToFile(csvData, './data.csv');
const fileContent = converter.readFromFile('./data.csv'); console.log('File Content:\n', fileContent);
- Convert File Formats
converter.convertFromFile('./data.csv', 'csv', 'json');