Home > Enterprise >  I got my JSON, now I need it to download inot an specific directory
I got my JSON, now I need it to download inot an specific directory

Time:05-09

I have an API that periodically makes a request to RESTAPI and stores the data into my database, now I want to add a new feature for certain data: download some data by a request to my API, then, my API makes another request to the RESTAPI, but I dont want this data to store in my database I want it to download as JSON or CSV.

I managed to create the request, I coded the request to the RESTAPI and managed to get the JSON into a variable with all the data, Im stuck there, How do I make this data to get downloaded into a direcory?

Im using javascript nodeJS with bent ,getJSON ,mssql ,https.

the code of the function:

async function descargarDatosOpendata(anioIni, anioFin, Indicativo){
try{
while(anioIni == anioFin || anioIni < anioFin){
    console.log("first");
    var http = require("https");
    var options = {
        "method": "GET",
        "hostname": "opendata.aemet.es",
        "path": "/opendata/api/valores/climatologicos/mensualesanuales/datos/anioini/"  anioIni  "/aniofin/"  anioIni  "/estacion/"  Indicativo  "",
        "headers": {
            "cache-control": "no-cache",
            "api_key": "MYKEY"
        }
    };
    console.log("second");
    var req = http.request(options, function (res) {
        console.log("tercera");
        var chunks = [];
        res.on("data", function (chunk) {
            chunks.push(chunk);
        });
        res.on("end", async function () {       
            console.log("endChunk");
            var body = Buffer.concat(chunks);
            console.log(body);
            var bodyString = body.toString();
            bodyJSON = JSON.parse(bodyString);
            console.log(bodyJSON);
            console.log(bodyJSON.datos);
            if (bodyJSON.estado == 200 && bodyJSON.descripcion == "exito") {
                let obj = await getJSON(bodyJSON.datos);
                console.log(obj)
                        
            
            }
        });
    });
    anioIni  ;
req.end();
}
} 
catch (err) {
    console.log(err);
}

}

obj log is the data in json format: [{data}]

CodePudding user response:

If this code is running in Node, you should use the Node fs module. The appendFile method will create a new file or append to it if it already exists. Learn more about fs

Example code

var fs = require('fs');

fs.appendFile('mynewfile1.txt', 'Hello content!', function (err) {
  if (err) throw err;
  console.log('Saved!');
});
  • Related