Search code examples
javascriptnode.jsfspapaparse

How to resolve weird output while reading data from a CSV file in javascript?


I am reading a csv file and wants to convert into a string of array. My file looks like this:

https://www.google.com/imghp?hl=en&tab=wi
https://maps.google.com/maps?hl=en&tab=wl
https://play.google.com/?hl=en&tab=w8
https://www.youtube.com/?gl=US&tab=w1
https://news.google.com/nwshp?hl=en&tab=wn
https://mail.google.com/mail/?tab=wm
https://drive.google.com/?tab=wo
https://www.google.com/intl/en/about/products?tab=wh
https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.com/
https://www.google.com/url?q=https://lifeinaday.youtube/%3Futm_source%3Dgoogle%26utm_medium%3Dhppcta%26utm_campaign%3D2020&source=hpp&id=19019062&ct=3&usg=AFQjCNEJMAD58Mjdnro8Mjm-RtJ3nfEIZA&sa=X&ved=0ahUKEwi98PWM4-HqAhVh1uAKHeYGCPwQ8IcBCAU

I am running this code to read the above csv file and pushing the data into csv_data array

const fs = require('fs');
const Papa = require('papaparse');

const csvFilePath = 'anchors.csv'

const file = fs.createReadStream(csvFilePath);

var csvData=[];
Papa.parse(file, {
  header: true,
  step: function(result) {
    csvData.push(result.data)
  },
  complete: function(results, file) {
    console.log('Complete', csvData.length, 'records.'); 
    console.log(csvData)
  }
});

However, I am getting this weird output seperated with colons and curly brackets.

[  
  {
    'https://www.google.com/imghp?hl=en&tab=wi': 'https://maps.google.com/maps?hl=en&tab=wl'
  },
  {
    'https://www.google.com/imghp?hl=en&tab=wi': 'https://play.google.com/?hl=en&tab=w8'
  },
  {
    'https://www.google.com/imghp?hl=en&tab=wi': 'https://www.youtube.com/?gl=US&tab=w1'
  },
  {
    'https://www.google.com/imghp?hl=en&tab=wi': 'https://news.google.com/nwshp?hl=en&tab=wn'
  },
  {
    'https://www.google.com/imghp?hl=en&tab=wi': 'https://mail.google.com/mail/?tab=wm'
  },
  {
    'https://www.google.com/imghp?hl=en&tab=wi': 'https://drive.google.com/?tab=wo'
  },
  {
    'https://www.google.com/imghp?hl=en&tab=wi': 'https://www.google.com/intl/en/about/products?tab=wh'
  },
  {
    'https://www.google.com/imghp?hl=en&tab=wi': 'https://accounts.google.com/ServiceLogin?hl=en&passive=true&continue=https://www.google.com/'
  },
  {
    'https://www.google.com/imghp?hl=en&tab=wi': 'https://www.google.com/url?q=https://lifeinaday.youtube/%3Futm_source%3Dgoogle%26utm_medium%3Dhppcta%26utm_campaign%3D2020&source=hpp&id=19019062&ct=3&usg=AFQjCNEJMAD58Mjdnro8Mjm-RtJ3nfEIZA&sa=X&ved=0ahUKEwi98PWM4-HqAhVh1uAKHeYGCPwQ8IcBCAU'
  }
]

What am i doing wrong here. I just need the whole string separated by comma.Any help would be appreciated.Thanks.


Solution

  • Nothing wrong here, in a CSV file, the first line is for the header-row (the name of your columns). Here you have a column named 'https://www.google.com/imghp?hl=en&tab=wi', all subsequent lines are value-rows.

    try passing header: false.