jsonToCsv helper

master
sundowndev 2019-02-27 17:03:03 +01:00
parent fa1e98ce4d
commit 41846ce600
2 changed files with 60 additions and 1 deletions

View File

@ -0,0 +1,56 @@
const escapeCsv2 = async (x) => {
if (x) {
return ('' + x).replace( /[",\n\r]/gi, '' );
}
else {
return ('');
}
}
const jsonToCsv2 = async (data, cb) => {
var keys = Object.keys(data[0]);
var csv = [keys.join(",")];
console.time("CSVGeneration");
data.forEach(function (row) {
var line = '';
keys.forEach(function (key) {
if (typeof row[key] === 'string') {
row[key] = "" + escapeCsv(row[key]) + "";
}
line += row[key] + ",";
});
csv.push(line);
});
console.timeEnd("CSVGeneration");
csv = csv.join("\n");
return csv;
}
const escapeCsv = (x) => {
if (x) return ('' + x.replace(/"/g, '').replace(/,/g, ' ').replace(/\n/g, " ").replace(/\r/g, " ") + '');
else return ('');
}
const jsonToCsv = (data) => {
var keys = Object.keys(data[0]),
csv = [keys.join(",")];
var row;
for (var i = 0; i < data.length; i++) {
row = [];
for (var j = 0; j < keys.length; j++) {
if (typeof data[i][keys[j]] === 'string') {
row.push('"' + escapeCsv(data[i][keys[j]]) + '"');
} else {
row.push(data[i][keys[j]]);
}
}
csv.push(row.join(','));
}
return csv.join("\n");
}
module.exports = () => ({
parse: jsonToCsv,
});

View File

@ -2,6 +2,7 @@ const path = require('path');
const immersive = require('immersive');
const req = require('./helpers/request');
const jsonToCsv = require('./helpers/jsonToCsv');
const config = {
// Application name used for config persistence (required)
@ -21,10 +22,12 @@ const config = {
},
helpers: {
req,
jsonToCsv,
}
};
global.user = {};
global.rootPath = path.dirname(__filename);
global.user = {}
global.data = {};
immersive(config);