I made some changes in how the function behaves, now I validate with 2 methods if there is a header, if it exists I ignore it and add the rows, if not I add the header, remove the quotation marks from the objects and pass some awaits, because the function it was sync and there was no await so it didn't make sense to be async hahaha
The CSV value passed to filename is the name of the folder that the node will look for in the project's root to save your final document
Fiz umas mudanças em como a função se comporta, agora eu valido com 2 métodos se existe cabeçalho, se existir eu ignoro ele e adiciono as rows, se não eu adiciono o cabeçalho, removi as aspas dos objetos e passe uns awaits, porque a função era sync e não tinha nenhum await então não fazia sentido ser async hahaha
O valor CSV passado para o nome do arquivo é o nome da pasta que o nó procurará na raiz do projeto para salvar seu documento final
const fs = require("fs");
const path = require("path");
const json2csv = require("json2csv").parse;
// Constructor method to assist our ReadFileSync
const readFileSync = filePath =>
fs.readFileSync(filePath, { encoding: "utf-8" });
// A helper to search for values in files =D
const findWord = async (text, filePath) => {
const result = await readFileSync(path.join(__dirname, filePath));
return Promise.resolve(RegExp("\\b" + text + "\\b").test(result));
};
const write = async (fileName, fields, data) => {
// output file in the same folder
const filename = path.join(__dirname, "CSV", `${fileName}`);
let rows;
// I check if there is a header with these items
const hasValue = await findWord("Name,Position,Salary", "./CSV/test.csv");
// If there is a header I add the other lines without it if I don't follow the natural flow
if (hasValue) {
rows = json2csv(data, { header: false });
} else if (!fs.existsSync(fields)) {
// If file doesn't exist, we will create new file and add rows with headers.
rows = json2csv(data, { header: true });
} else {
// Rows without headers.
rows = json2csv(data, { header: false });
}
// I deal with the information by removing the quotes
const newRows = rows.replace(/[\\"]/g, "");
// Append file function can create new file too.
await fs.appendFileSync(filename, newRows);
// Always add new line if file already exists.
await fs.appendFileSync(filename, "\r\n");
};
fields = ["Name", "Position", "Salary"];
data = [
{
Name: "Test1",
Position: "Manager",
Salary: "$10500",
},
{
Name: "Test2",
Position: "Tester",
Salary: "$5500",
},
{
Name: "Test3",
Position: "Developer",
Salary: "$5500",
},
{
Name: "Test4",
Position: "Team Lead",
Salary: "$7500",
},
];
write("test.csv", fields, data);
Output:
"Name","Position","Salary"
"Test1","Manager","$10500"
"Test2","Tester","$5500"
"Test3","Developer","$5500"
"Test4","Team Lead","$7500"