I want to generate a .json file on my local project folder. I want to save the fetch API call response (which is an array of objects) into a .json file on my hard disc. Here is my code :
const fs = require('fs');
export default function getdirectory(token) {
return fetch(url, {
headers: {Authorization: "Bearer " + token}
})
.then((response) => response.json())
.catch((err) =>{
console.log("ERORRRRRRRR @@@@@@" + err);
})
.then((response) => {
//console.log(response);
var jsoncontent = JSON.stringify(response);
//console.log(jsoncontent);
fs.writeFileSync('files-to-cache.json', jsoncontent, function(err) {
if (err)
{console.log("EROROROROROR ****" + err);}
else
{ return response;}
});
// return response;
})
.catch((err) =>{
console.log("ERORRRRRRRR $$$$$$" + err);
})
};
When I run the code in vs code I get the following error:
undefined is not a function (near '...fs.writeFileSync...')
It seems that it happens because the data is not ready at the time of json file creation (asynchronous). Some web sites recommend setTimeOut function or sf.writeFileSync instead of sf.writeFile. I tried both, but still it doesn't work. Would you please help me to resolve this problem? Many thanks