Fetch json data from url and write in a file

4.5k views Asked by At

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

2

There are 2 answers

1
Liam Stojanovic On BEST 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.

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'))
    })
})
2
Roman Gavrilov On

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.");
        });
    }