0

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);

1 Answer 1

1

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);
  });

});

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.