ryu1kn / csv-writer

Convert objects/arrays into a CSV string or write them into a CSV file
https://www.npmjs.com/package/csv-writer
MIT License
246 stars 39 forks source link

Prints empty lines when used with continuous data flow #29

Closed cozzbie closed 5 years ago

cozzbie commented 5 years ago

If I try to pass structured data into this during a continuous operation, it fails to enter the record and only empty contents are passed to the csv. eg


async function(){
   for(const record of records) {
        await csvWriter.writeRecords(record);
   }
}

I know its better to just pass the entire the record into it, but this is for illustration like an ongoing http request process that keeps recurring.

ryu1kn commented 5 years ago

Hi @cozzbie , as the name suggests, writeRecords expects a list of records; so you need to call it like .writeRecords([record]).

If you run this script and open out.csv while the script is running, you should see the contents growing line-by-line.

// app.js
const {createObjectCsvWriter} = require('csv-writer')

async function main () {
  const csvWriter = createObjectCsvWriter({
    path: 'out.csv',
    header: ['name', 'age'].map(f => ({id: f, title: f.toUpperCase()}))
  })
  const records = [...new Array(50)]
    .map((_value, i) => ({name: `foo-${i}`, age: i}))

  for (const record of records) {
    await csvWriter.writeRecords([record]);
    await new Promise(resolve => setTimeout(resolve, 1000))
  }
}

main().catch(e => {
  setTimeout(() => { throw e }, 0)
})
cozzbie commented 5 years ago

Damn!!! Thanks