I have a link of csv. So what i want is when my page load for the first time i want to download the csv file from a link and store it on public folder.So that i can take it from there and map its data by converting it into JSON.
First of all you need an express server. After that, create a file csv.js (maybe inside the "utils" folder) in your backend. Inside write this code:
const {
readJSON,
writeJSON,
writeFile,
readFile,
remove,
createReadStream,
createWriteStream,
} = fs;
import fs from "fs-extra";
import { fileURLToPath } from "url";
import { dirname, join } from "path";
const authorsJSONPath = join(
dirname(fileURLToPath(import.meta.url)),
"../authors.json"
);
export const getAuthorsReadableStream = () => createReadStream(authorsJSONPath);
Then of course you need the server, and the routes. Import the router in your server and specify an endpoint. If you know how to do that, create this route and import what you need. You will need the package json2csv
import json2csv from "json2csv";
// Get CSV files
router.get("/download/csv", async (req, res, next) => {
try {
res.setHeader("Content-Disposition", `attachment; filename=Authors.csv`);
const source = getAuthorsReadableStream();
const transform = new json2csv.Transform({
fields: ["id", "name", "surname", "email", "dateOfBirth", "avatar"],
});
const destination = res;
pipeline(source, transform, destination, (err) => {
if (err) next(err);
});
} catch (error) {
next(error);
}
});
If you want to just have that data to map through it, and not to be downloaded by the user, create a JSON file and map through it instead.
For any further support or issue just ask here.