Do we always need the backend?
In order to perform this simple task, we all know that the effort could be sometime not as light as it might look. As an example, exporting a csv in PHP is not so simple, and of course usually we use the backend in order to perform this operation. But what if we could use the client? Let's say that as an example, we're using a web app that fetches all users' data of an application from the backend , maybe with an heavy query. Our customer asks to implement a feature in order to download the table of the users. The process would be:
- Admin asks to the server the user's table.
- server performs the query and fetches the result.
- Admin asks to the server the csv of the table.
- Server performs another time the query, and respond with a csv. With a little bit of work, this can be done all in the client.
Filesaver Js
Using this library we can implement this common feature in the frontend (or in our node project, if we need to). In this article, i am going to explain how to use it on our frontend. First, you may want to check the project at this link.
A quick and exaustive example
In this example we are going to export some users data. First, we must import the library from a CDN:
<html lang="it" dir="ltr">
<head>
<meta charset="utf-8">
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/2.0.0/FileSaver.min.js" integrity="sha512-csNcFYJniKjJxRWRV1R7fvnXrycHP6qDR21mgz1ZP55xY5d+aHLfo9/FcGDQLfn2IfngbAHd8LdfsagcCqgTcQ==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
<title>Example</title>
</head>
<body>
<!-- your body -->
</body>
</html>
then, after implementing a button, we can use this script to perform a csv download:
const button = document.getElementById('download-button');
button.addEventListener('click', generateCSV);
function generateCSV() {
let csv = "";
let csvHeaders = "";
const arrayOfObjects = //YOUR ARRAY OF OBJECTS HERE;
// set csv headers using the first object keys
Object.keys(arrayOfObjects[0]).map((header) => {
csvHeaders += header + ", "
})
csv = csvHeaders;
//create csv rows
arrayOfObjects.map((row) => {
csv += `\r\n ` + Object.values(row).join(",");
})
// removes the last comma
csvHeaders = csvHeaders.slice(0,-2)
console.log(csv);
var blob = new Blob([csv], {type: "text/plain;charset=utf-8"});
//download your csv
saveAs(blob,"title_report.csv");
</script>
Comments (0)