Home > OS >  How to save data fetched from API with JavaScript
How to save data fetched from API with JavaScript

Time:08-10

I want to save fetched data to a file, but when program is finished the file contains only two curly brackets "{}". No errors, successfully compiled.

When I try to save data to a variable, the variable contains Promise { <pending> }.

But if we run getData().then(data => console.log(data.foods[0].foodNutrients));, everything works fine and we see the data in console.

How to save the data?

const fetch = require("node-fetch");
const fs = require('fs');

const params = {
    api_key: 'i8BGQ3wZNm7Urp1Vb5ly2mfVPcHprcweMGPasvXD',
    query: 'carrot, raw',
    dataType: ['Survey (FNDDS)'],
    pagesize: 1,
}

const api_url = 
`https://api.nal.usda.gov/fdc/v1/foods/search?api_key=${encodeURIComponent(params.api_key)}&query=${encodeURIComponent(params.query)}&dataType=${encodeURIComponent(params.dataType)}&pageSize=${encodeURIComponent(params.pagesize)}`

function getData() {
    return fetch(api_url).then(response => response.json())
};
   
const nutrients = getData().then(data => data.foods[0].foodNutrients);

fs.writeFile('/Users/Mark/Desktop/scrap/output.txt', JSON.stringify(nutrients), function(err) {
    if(err) {
        return console.log(err);
    }
    console.log("The file was saved!");
});

CodePudding user response:

Fetch is async so data is received inside the then() block, you can write your file in there:

const fetch = require("node-fetch");
const fs = require('fs');

const params = {
    api_key: 'i8BGQ3wZNm7Urp1Vb5ly2mfVPcHprcweMGPasvXD',
    query: 'carrot, raw',
    dataType: ['Survey (FNDDS)'],
    pagesize: 1,
}

const api_url = 
`https://api.nal.usda.gov/fdc/v1/foods/search?api_key=${encodeURIComponent(params.api_key)}&query=${encodeURIComponent(params.query)}&dataType=${encodeURIComponent(params.dataType)}&pageSize=${encodeURIComponent(params.pagesize)}`

function getData() {
    return fetch(api_url).then(response => response.json())
};
   
const nutrients = getData().then(data => {
    let myData = data.foods[0].foodNutrients;

    fs.writeFile('/Users/Mark/Desktop/scrap/output.txt', JSON.stringify(myData), function(err) {
        if(err) {
            return console.log(err);
        }
        console.log("The file was saved!");
    });
});
  • Related