I am starting to develop with Node JS
and I am creating an application to achieve the following:
Download a CSV with the JSON information found in an API. I have an internal file that contains the url where the JSON is located, I need to extract the information from that url and download it in CSV. I am using the json-2-csv
, node-fetch
and fs
modules.
My problem: I cannot access the information contained in the JSON to download it
This is my controller
:
import { Request, Response } from 'express';
const converter = require("json-2-csv");
const fetch = require("node-fetch");
const fs = require("fs");
class IndexController {
public async index(req: Request, res: Response) {
const api =req.query.api; //api1
const url = conf.API_MOCS[`${api}`].url; //url containing the json
const getJson = async () => {
const response = await fetch(url);
const responseJson = await response.json();
return responseJson;
};
}
}
export const indexController = new IndexController();
The problem is that you never call your
getJson
function, i.e. a call likeconst jsonResponse = await getJson()
is missing. It's not really necessary to do this in a separate function though. After getting the json, you need to pass it to thecsv
-converter and finally send the response through theres
-object.Here's a simplifed example (still needs error-handling) that fetches a json from a fake rest-api and converts it to csv and allows the user to download it: