Reputation: 3
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
Upvotes: 0
Views: 5886
Reputation: 36
jsondata
is a redundant variable. Here is a rewrite of your fetch().then().then()
which leverages fs.writeFile()
in the second .then()
.
I used node-fetch
for this implementation, but it should work in a browser environment as well.
fetch('http://somewebsite.null')
.then((response) => {
return response.json();
})
.then((json) => {
fs.writeFile('./test.json', JSON.stringify(json), (err) => {
if (err) {
throw new Error('Something went wrong.')
}
console.log('JSON written to file. Contents:');
console.log(fs.readFileSync('test.json', 'utf-8'))
})
})
Upvotes: 1
Reputation: 632
you can get a fetch result with async/await
. writeFile
should be called after get a fetch result
async function write(){
let jsondata;
const response = await fetch('www....');
jsondata = await response.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.");
});
}
Upvotes: 0