Skip to content

Instantly share code, notes, and snippets.

@simone-sanfratello
Created June 27, 2018 08:47
Show Gist options
  • Save simone-sanfratello/8b6bbc53041eff280d751171f607c201 to your computer and use it in GitHub Desktop.
Save simone-sanfratello/8b6bbc53041eff280d751171f607c201 to your computer and use it in GitHub Desktop.
query result to csv
const fs = require('fs-extra')
function csv (result, file) {
const _content = []
let _header = false
for (const row of result) {
const _line = []
for (const field in row) {
if (!_header) {
_line.push('"' + field + '"')
}
_line.push(row[field])
}
_header = true
_content.push('"' + _line
.map(s => s.replace('"', '\\"'))
.join('","') + '"')
}
fs.writeFile(file, _content.join('\n'), (err) => {
if (err) {
console.error(err)
return
}
console.log('write file', file)
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment