1 $("#download_1").click(function() {
2var json_pre = '[{"Id":1,"UserName":"Sam Smith"},{"Id":2,"UserName":"Fred Frankly"},{"Id":1,"UserName":"Zachary Zupers"}]';
3var json = $.parseJSON(json_pre);
4
5var csv = JSON2CSV(json);
6var downloadLink = document.createElement("a");
7var blob = new Blob(["\ufeff", csv]);
8var url = URL.createObjectURL(blob);
9downloadLink.href = url;
10downloadLink.download = "data.csv";
11
12document.body.appendChild(downloadLink);
13downloadLink.click();
14document.body.removeChild(downloadLink);
15});
1function JSON2CSV(objArray) {
2 var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
3 var str = '';
4 var line = '';
5
6 if ($("#labels").is(':checked')) {
7 var head = array[0];
8 if ($("#quote").is(':checked')) {
9 for (var index in array[0]) {
10 var value = index + "";
11 line += '"' + value.replace(/"/g, '""') + '",';
12 }
13 } else {
14 for (var index in array[0]) {
15 line += index + ',';
16 }
17 }
18
19 line = line.slice(0, -1);
20 str += line + '\r\n';
21 }
22
23 for (var i = 0; i < array.length; i++) {
24 var line = '';
25
26 if ($("#quote").is(':checked')) {
27 for (var index in array[i]) {
28 var value = array[i][index] + "";
29 line += '"' + value.replace(/"/g, '""') + '",';
30 }
31 } else {
32 for (var index in array[i]) {
33 line += array[i][index] + ',';
34 }
35 }
36
37 line = line.slice(0, -1);
38 str += line + '\r\n';
39 }
40 return str;
41}
1const file1 = 'one.csv';
2const file2 = 'two.csv';
3const stream = fs.createReadStream(file1);
4const stream2 = fs.createReadStream(file2);
5const fileData1 = [];
6const fileData2 = [];
7
8const file1Promise = new Promise((resolve) => {
9 csv
10 .parseFile(file1, {headers: true})
11 .on('data', function(data) {
12 fileData1.push(data);
13 })
14 .on('end', function() {
15 console.log('done');
16 resolve();
17 });
18});
19
20const file2Promise = new Promise((resolve) => {
21 csv
22 .parseFile(file2, {headers: true})
23 .on('data', function(data) {
24 fileData2.push(data);
25 })
26 .on('end', function() {
27 console.log('done');
28 resolve();
29 });
30});
31
32Promise.all([
33 file1Promise,
34 file2Promise,
35])
36 .then(() => {
37 const fileData3 = fileData1.concat(fileData2);
38 console.log(fileData3);
39
40 const csvStream = csv.format({headers: true});
41 const writableStream = fs.createWriteStream('outputfile.csv');
42
43 writableStream.on('finish', function() {
44 console.log('DONE!');
45 });
46
47 csvStream.pipe(writableStream);
48 fileData3.forEach((data) => {
49 csvStream.write(data);
50 });
51 csvStream.end();
52 });
53