i try to download a file in an interval of 24hours. To test the program, i need to run my function for download the program. But, each time im running my function i have this error : TypeError: Cannot read properties of undefined (reading 'checksum') at Timeout.onDownload
here is the function :
require('isomorphic-fetch')
const converterCsvToJson = require("csvtojson");
const fs = require('fs');
const path = require('path');
const PATH_FOLDER_DOWNLOAD = path.join(__dirname, "./files");
if(!fs.existsSync(PATH_FOLDER_DOWNLOAD)) {
fs.mkdirSync(PATH_FOLDER_DOWNLOAD);
}
const TIME_DOWNLOAD_INTERVAL = ((1_000 * 60) * 60) * 24; // 24 hours
const downloadRid = setInterval(onDownload, TIME_DOWNLOAD_INTERVAL);
async function onDownload() {
const response = await fetch('https://www.data.gouv.fr/api/2/datasets/6010206e7aa742eb447930f7/resources/?page=1&type=main&page_size=1', {
method: "GET"
});
const data = response.json();
const lastItem = data[0];
const integrity = lastItem.checksum.value;
const filenames = fs.readdirSync(PATH_FOLDER_DOWNLOAD, {encoding: "utf-8"});
const exists = filenames.find(filename => (
filename.indexOf(integrity) !== -1
));
if(exists) {
const {published} = lastItem;
console.log(`opération annulé, aucun fichier à été publié depuis le: ${published}`);
} else {
const urlCsvFile = lastItem.url;
const response = await fetch(urlCsvFile, {method: "GET"});
const csvContent = await response.text();
fs.writeFileSync(
path.join(PATH_FOLDER_DOWNLOAD, (integrity + ".csv")),
csvContent,
{encoding: "utf-8"}
);
const json = await converterCsvToJson().fromString(csvContent);
console.log(json);
}
}
onDownload();
thanks for your help, have a good day
Looking manually at the response from the endpoint you're looking at: https://www.data.gouv.fr/api/2/datasets/6010206e7aa742eb447930f7/resources/?page=1&type=main&page_size=1 - it's clear that this is a JSON object (as is standard for most APIs), rather than an array as you're expecting when you index with const lastItem = data[0];.
The array of data that you seem to want - it includes objects with a checksum property - is held in the data property of the JSON object.
So you just need to replace this:
const lastItem = data[0];
with
const lastItem = data.data[0];