Estoy tratando de obtener datos Json de una URL y luego escribir los datos en un archivo Json. Aquí está mi código:
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."); });Pero estoy atascado con este error ya que los datos que quiero escribir en mi archivo parecen tener un argumento no válido mientras uso JSON.stringify. ¿Alguien tiene una idea?
Muchas gracias por tu ayuda !
TypeError [ERR_INVALID_ARG_TYPE]: el argumento de "datos" debe ser de tipo cadena o una instancia de Buffer, TypedArray o DataView. Recibido indefinido
puede obtener un resultado de búsqueda con async/await . Se debe llamar a writeFile después de obtener un resultado de búsqueda.
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."); }); }jsondata es una variable redundante. Aquí hay una reescritura de su fetch().then().then() que aprovecha fs.writeFile() en el segundo .then() .
Usé node-fetch para esta implementación, pero también debería funcionar en un entorno de navegador.
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')) }) })