0

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

1 Answer 1

2

You are using the incorrect version of write file, there are two different types, see below:

The first is writeFileSync, this is synchronous, and will block the thread, meaning your script cannot continue until it is finished, but most importantly it doesn't accept a call back...

Try this instead:

  fs.writeFile('data.json', jsonData, 'utf8', (err) => {
    if (err) throw err
    console.log('File created!`)
  })

Hope this helps.

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

1 Comment

Thank you very much Lloyd for your guidance. I tried the code you provided, but unfortunately I still receive the same error : undefined is not a function (near '...fs.writeFile...')

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.