Last active
July 23, 2019 19:55
-
-
Save crazy4groovy/cdebe70695d7cae8ae0abde952e17650 to your computer and use it in GitHub Desktop.
csv-stringify promisified wrapper
This file contains 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
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 | |
} | |
} |
This file contains 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
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