I'm trying to fetch Json data from a Url and then write the data in a Json File. Here is my code :
let jsondata;
fetch('www....')
.then(function(u){
return u.json();
})
.then(function(json) {
jsondata = json;
});
const fs = require('fs');
// write JSON string to a file
fs.writeFile('test.json', JSON.stringify(jsondata), (err) => {
if (err) {
throw err;
}
console.log("JSON data is saved.");
});
But I'm stuck with this error as the data I want to write in my file seems to have an invalid argument while I use JSON.stringify. Someone got an idea ?
Thanks a lot for your help !
TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received undefined
jsondata
is a redundant variable. Here is a rewrite of yourfetch().then().then()
which leveragesfs.writeFile()
in the second.then()
.I used
node-fetch
for this implementation, but it should work in a browser environment as well.