Search code examples
node.jstypescriptapijson2csv

How to download a CSV with the information of an external JSON in Node JS?


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(); 

Solution

  • The problem is that you never call your getJson function, i.e. a call like const 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 the csv-converter and finally send the response through the res-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:

    const express = require("express");
    const app = express();
    const port = 3000;
    
    const converter = require("json-2-csv");
    const fetch = require("node-fetch");
    
    app.get("/", async (req, res) => {
      const url = "https://jsonplaceholder.typicode.com/users";
      const response = await fetch(url);
      const jsonResponse = await response.json();
    
      const csvString = await converter.json2csvAsync(jsonResponse);
      res.setHeader("Content-disposition", "attachment; filename=data.csv");
      res.set("Content-Type", "text/csv");
      res.status(200).send(csvString);
    });
    
    app.listen(port, () => {
      console.log(`Example app listening at http://localhost:${port}`);
    });