bloppit bloppit - 1 month ago 5x
Node.js Question

Why isn't my CSV being written without any data?

I'm writing a function which takes in the results of a web scrape that I've performed on a tshirt website.

Each tshirt, has been stored as an object, with a title, price, imgUrl, URL and time. Each of these objects is stored in an array, holding all the tshirts.

In this function, I first convert the array to a JSON string. I console log this, just to check this is being done correctly.

I then create the folder if it doesn't already exist called data.

I list the fields I want for the CSV.

I then write the file by passing in my data (JSON string), the file path, and set it to overwrite.

Right now, when I call the function, it does all it's required to, except, when I open up the CSV file, the columns are titled correctly, yet the table is completely empty.

Any ideas? I'd really appreciate your input, thank you!

Code is below:

var json2csv = require('json2csv');
var fs = require('fs');

var tshirtArray = [ { price: '$20',
img: 'img/shirts/shirt-107.jpg',
title: 'Logo Shirt, Teal',
url: '',
date: 'September 22nd 2016, 11:17:48 pm' },
{ price: '$25',
img: 'img/shirts/shirt-108.jpg',
title: 'Mike the Frog Shirt, Orange',
url: '',
date: 'September 22nd 2016, 11:17:48 pm' },
{ price: '$25',
img: 'img/shirts/shirt-105.jpg',
title: 'Mike the Frog Shirt, Yellow',
url: '',
date: 'September 22nd 2016, 11:17:48 pm' },
{ price: '$20',
img: 'img/shirts/shirt-106.jpg',
title: 'Logo Shirt, Gray',
url: '',
date: 'September 22nd 2016, 11:17:48 pm' } ];

function convertJson2Csv(){

//The scraper should generate a folder called `data` if it doesn’t exist.
var dir ='./data';


var tshirtJson = JSON.stringify(tshirtArray);

var fields = ['Title', 'Price', 'ImageURl', 'URL', 'Date'];

var csv = json2csv({ data: tshirtJson, fields: fields });


fs.writeFile('./data/file.csv', csv, {overwrite: true}, function(err) {
if (err) throw err;
console.log('file saved');



Your data object has lowercase keys. Your fields array has not.

var fields = ['Title', 'Price', 'ImageURl', 'URL', 'Date'];

JavaScript is case-sensitive. The field names must match the object keys.