File conversion from one format to another is one of the most common operations in many software projects. Node.js, with its extensive library of packages and tools, makes this process simple and efficient. In this article, we will see how to convert a CSV file to XML using Node.js.
To convert a CSV file to XML, we will use two packages:
csv-parser
to read and parse CSV files.xmlbuilder2
to create the XML file.
Install the packages with the command:
npm install csv-parser xmlbuilder2
Then, create the main code:
const fs = require('fs');
const csv = require('csv-parser');
const { create } = require('xmlbuilder2');
// Main function
function convertCsvToXml(csvFilePath, xmlFilePath) {
const data = [];
// Read the CSV file
fs.createReadStream(csvFilePath)
.pipe(csv())
.on('data', (row) => {
data.push(row); // Add each CSV row to the array
})
.on('end', () => {
// Convert the array of objects to XML
const xmlObj = {
root: {
record: data
}
};
const xml = create(xmlObj).end({ prettyPrint: true });
// Write the XML file
fs.writeFileSync(xmlFilePath, xml, 'utf8');
console.log(`Conversion complete! XML file saved at: ${xmlFilePath}`);
})
.on('error', (err) => {
console.error('Error reading the CSV:', err);
});
}
// File paths
const csvFilePath = 'input.csv'; // Replace with your CSV file
const xmlFilePath = 'output.xml'; // Output XML file name
// Start conversion
convertCsvToXml(csvFilePath, xmlFilePath);
Create an input.csv
file with the sample content:
name,age,city
Alice,30,New York
Bob,25,Los Angeles
Charlie,35,Chicago
Run the code, and if everything is set up correctly, you will see a message confirming the creation of the XML file. The output.xml
file should look something like this:
<?xml version="1.0"?>
<root>
<record>
<name>Alice</name>
<age>30</age>
<city>New York</city>
</record>
<record>
<name>Bob</name>
<age>25</age>
<city>Los Angeles</city>
</record>
<record>
<name>Charlie</name>
<age>35</age>
<city>Chicago</city>
</record>
</root>
Conclusion
Converting a CSV file to XML with Node.js is a simple process thanks to the csv-parser
and xmlbuilder2
packages. This technique can be used in various applications, such as data integration or format migration.