Created
September 29, 2021 14:33
-
-
Save arsu-leo/6e668923f8e4c5f9a9e8e41468106a3b to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function processRow(row, fields, fieldSeparator) | |
{ | |
const | |
outRow = [], | |
keys = Array.isArray(row) | |
? Object.keys(row) | |
: (fields || Object.keys(row)); | |
for(let j = 0; j < keys.length; j++) | |
{ | |
const val = row[keys[j]]; | |
let innerValue = val === null || val === undefined | |
? '' | |
: val.toString(); | |
if (val instanceof Date) | |
{ | |
innerValue = val.toLocaleString(); | |
} | |
let result = innerValue.replace(/"/g, '""'); | |
if (result.search(/("|,|;|\n)/g) >= 0) | |
{ | |
result = '"' + result + '"'; | |
} | |
outRow.push(result); | |
} | |
return outRow.join(fieldSeparator); | |
} | |
module.exports = function (rows, fields, fieldSeparator = ',', rowSeparator = "\r\n") | |
{ | |
//Setup fields | |
const kfields = fields | |
? Array.isArray(fields) | |
? fields | |
: Object.keys(fields) | |
: undefined; | |
//Init csv output | |
return ( | |
fields | |
? processRow(fields, undefined, fieldSeparator) + rowSeparator | |
: '' | |
) | |
+ rows.map((row) => processRow(row, kfields, fieldSeparator)).join(rowSeparator); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment