Skip to content

Instantly share code, notes, and snippets.

@aleclarson
Created April 14, 2022 00:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aleclarson/c093c9dd8cba598a44a2cf6a4e5d8764 to your computer and use it in GitHub Desktop.
Save aleclarson/c093c9dd8cba598a44a2cf6a4e5d8764 to your computer and use it in GitHub Desktop.
const reservedChars = /[\r\n,"]/
module.exports = function toCSV(header, rows) {
rows = rows.map(row => row.map(valueToString).join(','))
return [header.join(','), ...rows].join('\r\n') + '\r\n'
}
function valueToString(value) {
return value === undefined
? ''
: (typeof value === 'string' && reservedChars.test(value)) ||
(typeof value === 'object' && value !== null)
? escapeString(value)
: value
}
function escapeString(value) {
let str = JSON.stringify(value)
if (typeof value === 'string') {
str = str.slice(1, -1)
}
str = str.replace(/"/g, '""')
return '"' + str + '"'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment