work with csv in javascript code example
Example 1: Working with CSV in JavaScript
const fs = require("fs");
const csv = require("csvtojson");
const { Parser } = require("json2csv");
(async () => {
const cars = await csv().fromFile("cars.csv");
console.log(cars);
cars[0].Year = 1998;
const carsInCsv = new Parser({ fields: ["Year", "Make", "Model", "Length"] }).parse(cars);
fs.writeFileSync("cars.csv", carsInCsv);
})();
Example 2: create csv file javascript
$("#download_1").click(function() {
var json_pre = '[{"Id":1,"UserName":"Sam Smith"},{"Id":2,"UserName":"Fred Frankly"},{"Id":1,"UserName":"Zachary Zupers"}]';
var json = $.parseJSON(json_pre);
var csv = JSON2CSV(json);
var downloadLink = document.createElement("a");
var blob = new Blob(["\ufeff", csv]);
var url = URL.createObjectURL(blob);
downloadLink.href = url;
downloadLink.download = "data.csv";
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
});