Skip to content

Instantly share code, notes, and snippets.

@crazy4groovy
Last active July 23, 2019 19:55
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 crazy4groovy/cdebe70695d7cae8ae0abde952e17650 to your computer and use it in GitHub Desktop.
Save crazy4groovy/cdebe70695d7cae8ae0abde952e17650 to your computer and use it in GitHub Desktop.
csv-stringify promisified wrapper
import * as stringify from 'csv-stringify'
module.exports = function (delimiter = ',') {
const data = []
const result = {str: undefined}
const stringifier = stringify({
delimiter
})
stringifier.on('readable', () => {
let row
while ((row = stringifier.read())) {
data.push(row)
}
})
stringifier.on('error', error => {
console.error('CSV Error "on":', error.message)
throw error
})
stringifier.on('finish', () => {
result.str = data.join('')
})
function setHeaders(headers) {
stringifier.write(headers)
}
function setRow(row) {
stringifier.write(row)
}
async function close() {
return new Promise(resolve => {
const afterFinish = () => resolve(result.str)
stringifier.end(afterFinish)
})
}
return {
close,
setHeaders,
setRow
}
}
const csvInit = require('./csv-writer.js')
const writer = csvInit()
writer.setHeaders(['Name', 'Age'])
writer.setRow(['Steve', 12])
const userCSV = await writer.close()
console.log({userCSV})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment