Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

115
Vistas
Fetch json data from url and write in a file

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

about 4 years ago · Juan Pablo Isaza
2 Respuestas
Responde la pregunta

0

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.");
        });
    }
about 4 years ago · Juan Pablo Isaza Denunciar

0

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'))
    })
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda