-2

How do you get the response from the fetch to write to a json file in the same directory, instead of the output to the console?

const sample = fetch('https://dummyapi.io/data/v1/user?limit=5&page=1', {
method: 'GET',
headers: {
    'app-id': '63e798a1498c3c5fa3e2faeb',
},
})
.then(response => response.json()) 
.then(json => console.log(json)); 

I'm able to get the results to display in the console, per the code above, the fetch appears to be working, but I'd like to have the response write a new file(Newfile.json) in the same directory in json format. After I'm able to do this I'd like to do the same but write it to .csv (Newfile.csv)

I've tried the code below from another post, it creates the file but the contents of the file is just {}

const obj = fetch('https://dummyapi.io/data/v1/user?limit=5&page=1', {
method: 'GET',
headers: {
'app-id': 'xxxxxx',
},
})

const fs = require('fs');
fs.writeFile("test.json", JSON.stringify(obj), function(err) {
if(err) {
return console.log(err);
}
console.log("The file was saved!");
});
jonrsharpe
  • 115,751
  • 26
  • 228
  • 437

1 Answers1

0

The file content is empty cause you are not writing anything to it. You need to first extract the data from the response and then write it to your file being created, the code below should help you.

const sample =  fetch('https://dummyapi.io/data/v1/user?limit=5&page=1', {
  method: 'GET',
  headers: {
    'app-id': 'xxxxxx',
  },
})
.then(response => response.json())
.then(data => {
  const fs = require('fs');
  fs.writeFile("test.json", JSON.stringify(data), function(err) {
    if(err) {
      return console.log(err);
    }
    console.log("The file was saved!");
  });
})
.catch(error => {
  console.error(error);
});

This should write the response to your test.json file but if you try to log the sample variable, it would return undefined because fetch is an async function and the writeFile function does not return anything, so the final then block in the chain of Promises does not have a value to resolve with.

High Zedd
  • 60
  • 7