Sure! Below is a TypeScript module that exports a function named mergeCsvFiles. This function takes a folder path as its parameter, reads all CSV files in that folder (assuming they have the same schema), merges their contents, and saves the merged result as a new CSV file in the same folder.
Prerequisites
-
Node.js and TypeScript Setup: Ensure you have Node.js and TypeScript installed in your project. If not, you can initialize a new Node.js project and install TypeScript:
npm init -y
npm install typescript @types/node --save-dev
npx tsc --init
-
CSV Parsing Library: We'll use csv-parser to parse CSV files and csv-writer to write the merged CSV. Install them using npm:
npm install csv-parser csv-writer
npm install @types/csv-parser --save-dev
TypeScript Code
Create a file named mergeCsv.ts and add the following code:
import * as fs from 'fs';
import * as path from 'path';
import csvParser from 'csv-parser';
import { createObjectCsvWriter } from 'csv-writer';
/**
* Merges all CSV files in the specified folder into a single CSV file.
* The merged file is saved as 'merged.csv' in the same folder.
*
* @param folderPath - The path to the folder containing CSV files.
* @returns A Promise that resolves when the merging is complete.
*/
export async function mergeCsvFiles(folderPath: string): Promise<void> {
// Verify that the provided path is a directory
if (!fs.existsSync(folderPath) || !fs.lstatSync(folderPath).isDirectory()) {
throw new Error(`The path "${folderPath}" is not a valid directory.`);
}
// Read all files in the directory
const files = fs.readdirSync(folderPath);
// Filter CSV files
const csvFiles = files.filter(file => path.extname(file).toLowerCase() === '.csv');
if (csvFiles.length === 0) {
throw new Error(`No CSV files found in the directory "${folderPath}".`);
}
const mergedData: any[] = [];
let headers: string[] | null = null;
// Function to read a single CSV file and return its data
const readCsv = (filePath: string): Promise<any[]> => {
return new Promise((resolve, reject) => {
const rows: any[] = [];
fs.createReadStream(filePath)
.pipe(csvParser())
.on('data', (data) => {
rows.push(data);
})
.on('end', () => {
resolve(rows);
})
.on('error', (error) => {
reject(error);
});
});
};
// Iterate through each CSV file and collect data
for (const csvFile of csvFiles) {
const fullPath = path.join(folderPath, csvFile);
try {
const data = await readCsv(fullPath);
if (headers === null && data.length > 0) {
headers = Object.keys(data[0]);
}
mergedData.push(...data);
} catch (error) {
console.error(`Error reading file "${csvFile}":`, error);
throw error;
}
}
if (headers === null) {
throw new Error('No data found in the CSV files.');
}
// Define the path for the merged CSV file
const mergedFilePath = path.join(folderPath, 'merged.csv');
// Initialize CSV writer
const csvWriter = createObjectCsvWriter({
path: mergedFilePath,
header: headers.map(header => ({ id: header, title: header })),
});
try {
await csvWriter.writeRecords(mergedData);
console.log(`Merged CSV saved to "${mergedFilePath}".`);
} catch (error) {
console.error('Error writing merged CSV file:', error);
throw error;
}
}
Explanation
-
Imports:
fs and path from Node.js for filesystem operations.
csv-parser to parse CSV files.
csv-writer to write the merged CSV file.
-
Function mergeCsvFiles:
- Parameter:
folderPath - the path to the directory containing CSV files.
- Validation: Checks if the provided path exists and is a directory.
- File Filtering: Reads all files in the directory and filters out only
.csv files.
- Reading CSV Files: Iterates through each CSV file, reads its content using
csv-parser, and collects the data. It also captures headers from the first CSV file to ensure consistency.
- Merging Data: Combines all rows from individual CSV files into a single array.
- Writing Merged CSV: Uses
csv-writer to write the merged data into a new file named merged.csv in the same directory.
-
Error Handling: The function includes error handling to manage scenarios like invalid directories, no CSV files found, read/write errors, etc.
Usage Example
You can use the mergeCsvFiles function in another TypeScript or JavaScript file as follows:
import { mergeCsvFiles } from './mergeCsv';
const folderPath = '/path/to/your/csv/folder';
mergeCsvFiles(folderPath)
.then(() => {
console.log('CSV files merged successfully.');
})
.catch((error) => {
console.error('An error occurred while merging CSV files:', error);
});
Compile and Run
-
Compile TypeScript to JavaScript:
Ensure your tsconfig.json is set up appropriately. Then compile:
npx tsc
-
Run the Script:
node dist/yourScript.js
Replace dist/yourScript.js with the actual path to your compiled JavaScript file.
Notes
- Header Consistency: This implementation assumes that all CSV files have the same headers/schema. If there are discrepancies, the merged CSV will follow the headers of the first CSV file.
- Merged File Naming: The merged file is named
merged.csv. If you run the function multiple times in the same directory, it will overwrite this file. Modify the mergedFilePath variable if you need different behavior.
- Large Files: For very large CSV files, you might need to handle streaming more efficiently to avoid high memory usage.
Dependencies
Ensure that your package.json includes the necessary dependencies:
{
"dependencies": {
"csv-parser": "^3.0.0",
"csv-writer": "^1.6.0"
},
"devDependencies": {
"@types/csv-parser": "^2.3.2",
"@types/node": "^20.5.1",
"typescript": "^5.1.6"
}
}
Install them using:
npm install
I hope this helps! Let me know if you have any questions or need further assistance.