Diego Delgado
Diego Delgado

Reputation: 155

Convert csv to json returning empty json file

I am trying to convert a csv file to json using the convert-csv-to-json package from npm. I am able to get the csv from the url and the 'data.csv' is created, but the corresponding json file is just an empty array. Am i calling the wrong file path, or is there some js quirks with promises that I am missing. I am pretty new to js.


const csvToJson = require('convert-csv-to-json');
const fs = require("fs");
const https = require("https");
const file = fs.createWriteStream("data.csv");



https.get("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_US.csv", response => {
  var stream = response.pipe(file);

  stream.on("finish", function() {
    console.log("done");
  });
});



const input = './data.csv'; 
const output = './data.json';

csvToJson.fieldDelimiter(',')
         .formatValueByType()
         .generateJsonFileFromCsv(input, output);

Upvotes: 0

Views: 283

Answers (1)

David Teather
David Teather

Reputation: 598

Javascript is asynchronous. Try the following code.

const csvToJson = require('convert-csv-to-json');
const fs = require("fs");
const https = require("https");
const file = fs.createWriteStream("data.csv");
const input = './data.csv'; 
const output = './data.json';



https.get("https://raw.githubusercontent.com/CSSEGISandData/COVID-19/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_US.csv", response => {
  var stream = response.pipe(file);

  stream.on("finish", function() {
    console.log("done");
    csvToJson.fieldDelimiter(',')
     .formatValueByType()
     .generateJsonFileFromCsv(input, output);
  });

});

Upvotes: 1

Related Questions