My code snippet works with node js but my actual file “LOCAL_JSON_FILE_PATH” does not update with the new data. I want to remove old data from the file and import new data at set times.
My code works because I see the console logs but my file “LOCAL_JSON_FILE_PATH” does not actually gain any data. What is wrong?
Console logs:
07-05 09:50:04
Local JSON file updated successfully at FILELOCATION.json
07-05 09:50:04
Updated file content: {
async function stepOne() {
try {
console.log('Fetching Knack record...');
const response = await fetch(API_URL_stepOne, {
method: 'GET',
headers: {
'X-Knack-Application-ID': APP_ID,
'X-Knack-REST-API-Key': API_KEY,
'Content-Type': 'application/json',
},
});
if (!response.ok) {
const errorText = await response.text();
console.error('Error response text:', errorText);
throw new Error(`Error fetching record: ${response.statusText} - ${errorText}`);
}
const data = await response.json();
return data.records[0];
} catch (error) {
console.error('Failed to fetch Knack record:', error);
throw new Error(`Failed to fetch Knack record: ${error.message}`);
}
}
async function stepTwo(url) {
try {
console.log('Downloading JSON data from URL:', url);
const response = await fetch(url);
if (!response.ok) {
throw new Error(`Failed to download JSON data: ${response.statusText}`);
}
const jsonData = await response.json();
console.log('Downloaded JSON data:', JSON.stringify(jsonData, null, 2));
fs.writeFile(LOCAL_JSON_FILE_PATH, JSON.stringify(jsonData, null, 2), 'utf8', (err) => {
if (err) {
console.error('Failed to update local JSON file:', err);
} else {
console.log(`Local JSON file updated successfully at ${LOCAL_JSON_FILE_PATH}`);
// Verify the content of the file
fs.readFile(LOCAL_JSON_FILE_PATH, 'utf8', (err, fileContent) => {
if (err) {
console.error('Failed to read updated file content:', err);
} else {
console.log('Updated file content:', fileContent);
}
});
}
});
} catch (error) {
console.error('Failed to update local JSON file:', error);
}
}
cron.schedule('*/5 * * * *', async () => {
try {
console.log('Running scheduled task...');
const record = await stepOne();
const url = record.field_13347_raw.url; // Extract the URL from the record
await stepTwo(url);
} catch (error) {
console.error('Error during scheduled task:', error);
}
}, {
scheduled: true,
timezone: "Europe/Madrid"
});