I’m trying to fetch Json data from a Url and then write the data in a Json File. Here is my code :
JavaScript
x
19
19
1
let jsondata;
2
fetch('www....')
3
.then(function(u){
4
return u.json();
5
})
6
.then(function(json) {
7
jsondata = json;
8
});
9
10
const fs = require('fs');
11
12
13
// write JSON string to a file
14
fs.writeFile('test.json', JSON.stringify(jsondata), (err) => {
15
if (err) {
16
throw err;
17
}
18
console.log("JSON data is saved.");
19
});
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
Advertisement
Answer
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.
JavaScript
1
14
14
1
fetch('http://somewebsite.null')
2
.then((response) => {
3
return response.json();
4
})
5
.then((json) => {
6
fs.writeFile('./test.json', JSON.stringify(json), (err) => {
7
if (err) {
8
throw new Error('Something went wrong.')
9
}
10
console.log('JSON written to file. Contents:');
11
console.log(fs.readFileSync('test.json', 'utf-8'))
12
})
13
})
14