Someone could help me ? I have to merge multiples csv files into one single csv file.
The csv files have the same header.
I'm using node.js and javascript.
Thank you
Some basic string manipulation will do well.
const fs = require("fs");
const path = require("path");
// get paths to file
const file1 = path.join(__dirname, "path/to/file1.csv"),
file2 = path.join(__dirname, "path/to/file2.csv");
// read the csv files
const csv1 = fs.readFileSync(file1),
csv2 = fs.readFileSync(file2);
// split the second csv by a new line then remove the first line (remove the header)
const [, ...rest] = csv2.split("\n");
const result = csv1 + rest.join("\n"); // combine csv
fs.writeFileSync(path.join(__dirname, "output.csv"), result); // write result to file
You can also do this dynamically:
// let's pretend you have an array of all the CSV text that you read from the file system named 'csv'
for(let i = 1; i < csv.length; i++) {
const [, ...spl] = csv[i].split("\n");
// instead of doing [, ...spl] we could also call: spl.shift();
csv[i] = spl.join("\n");
}
const result = csv.join("\n"); // our combined csv