Generating a CSV file with data from a collection in Meteor.js

I have successfully written the code to display a list of records on a webpage, but now I want to download it as a CSV (comma separated values) file.

Currently, the page is showing the list in the following format:

Name      Address      Description
Bob       1 street     Journalist
Bill      2 street     Fireman
etc...

Is there a way for meteor to generate a CSV file for download instead of displaying it on a webpage with HTML markup?

Answer №1

Referencing How to implement file download with iron router or meteor itself?

HTML:

<template name="example">
  <a href="{{pathFor 'csv'}}">Click here to download CSV</a>
</template>

JS:

// Sample collection
var SampleData = new Mongo.Collection("sampleData");

// generate some example data
if (Meteor.isServer) {
  Meteor.startup(function() {
    var sampleDataCursor = SampleData.find();
    if (sampleDataCursor.count() === 0) {
      for(var i=1; i<=50; i++) {
        SampleData.insert({Name: "Name" + i, Address: "Address" + i, Description:"Description" + i});
      }
    }
  });
}

Router.route('/csv', {
  where: 'server',
  action: function () {
    var filename = 'meteor_sampledata.csv';
    var fileData = "";

    var headers = {
      'Content-type': 'text/csv',
      'Content-Disposition': "attachment; filename=" + filename
    };
    var records = SampleData.find();
    // create a CSV string. Keep in mind you may need to handle quotes and commas.
    records.forEach(function(rec) {
      fileData += rec.Name + "," + rec.Address + "," + rec.Description + "\r\n";
    });
    this.response.writeHead(200, headers);
    return this.response.end(fileData);
  }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Cannot pass a Node/JS Promise to a variable using then statement

I am facing an issue with a promise in a class. Here is the code snippet: someMethod() { return new Promise(function(resolve) { resolve(10); } } Although I know that the value will be 10, I am trying to pass it to a variable called myvar ...

A guide on verifying the username, password, and chosen role from a database through the use of javascript/ajax or alternative validation methods

If the user's name, password, or role is incorrect, I want to display an error message using validations like AJAX/JavaScript. index.php <html> <head> </head> <body> <style> body { wi ...

The Angular controller failed to return a defined value

I recently took over a legacy VB.Net application and noticed that both the ng-app and ng-controller directives are present on the HTML element in the root master page: <html runat="server" id="html" ng-controller="MasterController"> The ng-app attr ...

Is it possible to create several XMLHttpRequests for various <li> elements upon clicking on them individually?

Today, I was experimenting with XMLHttpRequest to fetch news headlines from 10 different countries using the NewsAPI. I created 10 <li> tags for each country and assigned them an onclick function that triggers a JavaScript function to append the coun ...

Troubleshooting Vue Single File Components Displaying Missing Styles

I'm currently attempting to incorporate styles into a vuejs single file component. I've successfully achieved this in a node app previously, but now I am working with a python/flask backend (not that it should make a difference). The Vue componen ...

I am having trouble inserting a table from a JSON object into an HTML file

getJSON('http://localhost:63322/logs', function(err, data) { if (err !== null) { alert('Something went wrong: ' + err); } else { //var myObj = JSON.parse(data); // document.getElementById("demo").innerHTML = myObj.ad_soy ...

Using jQuery to display items from GitHub API in a custom unordered list format

Attempting to access data from the GitHub API using jQuery (AJAX) and display it on a static webpage. Here are the HTML and JS code snippets: $(document).ready(function(){ $.ajax({ url: 'https://api.github.com/re ...

Is there a way to effectively connect the back-end (utilizing MongoDB with Mongoose on an Express server in Node.js) with the front-end (using either Bootstrap or Foundation) in a

Can we connect: a backend created using a MongoDB database, accessed through Mongoose in a server built with Node.js and Express; a frontend designed with Bootstrap or Foundation, that dynamically responds to database queries. For example, displayi ...

Guide on emphasizing a div when the page's validity is not true

Is there a way to highlight a specific div when the page.isvalid=false? I can display the error message on page load, but struggling to highlight the required control. I have a JavaScript function that applies an error class to the div, which works fine w ...

Can you use ng-show within ng-if in Angular?

How can I make this input only show a property is true per the ng-if? The current code looks like this: <input type="button" class="naviaBtn naviaBlue" ng-if="ppt.Globals.hasDebitCard" ng-click="alertShow = (alertShow == 2 ? -1 : 2)" value="outstandin ...

Send information using jQuery AJAX

Currently, I am attempting to use AJAX to submit data to my table. Below is the form I have created for this purpose: <form> Total <input type="text" id="total" name="total" /><br /> Bill name<input type="text" id="bill-name" ...

PapaParse along with Highland are a powerful duo for handling

I am currently faced with the task of parsing a large CSV file in NodeJS and storing it in a database asynchronously, with a limit of 500 entries at a time. To overcome memory limitations, I need to stream the CSV file and have decided to utilize PapaParse ...

Receiving HTTP POST data using Classic ASP script

I'm currently working on a project and have come across an area where I am facing some challenges. Despite my best efforts, I haven't been able to find a solution using Google. In my ASP web application, I've added an HTML canvas that I nee ...

Updating the data and processing results settings for Select2 in an Angular 2 application

In my Angular2 app, I am utilizing Select2 and facing a challenge with accessing class properties in the data and processResults contexts. Unfortunately, these contexts do not belong to the class: export class DefaultFormInputSelectComponent { @Input ...

When individuals discuss constructing a stack, or a full stack, in JavaScript, what exactly are they referring to and how does this concept connect with Node JS?

I recently started learning about node.js, but I'm struggling to understand its purpose. I have experience with JavaScript/jQuery and Angular, so I don't see how Node can benefit me. People keep talking about full stack JavaScript but I'm st ...

Execute a function within a different function once the ajax call has been completed

There's an issue with the timing of my function that runs inside another function. It seems like sometimes the ajax call to the server isn't completed before the function is called. function obtainPlans(row, user, id, type) { $.get( "/ ...

What's the best way to retrieve a value from a function that invokes itself multiple times?

My task involves navigating through nested object data to find a specific result. I am using the findByKey function, which recursively calls itself until the desired result is found. However, instead of returning object.source, I am getting undefined. as ...

Navigating the use of PHP variables in JavaScript

Whenever I select an option from the menu, a Javascript function changes the input value based on a PHP variable. Below is an example of how I assign values from 1 to n to each option: $i = 0; foreach($videos as $val) { echo '<option value=&ap ...

The failure of a unit test involving Jest and try-catch

I am facing an issue with creating unit tests using jest. exportMyData.js const createJobTrasferSetArray = async () => { const data = exportData(); const jobTransferSet = []; try { data.forEach((element) => { const JobPathArray = el ...

Instructions for setting a default value for ng-options when dealing with nested JSON data in AngularJS

I need help setting a default value for my ng-options using ng-init and ng-model with dependent dropdowns. Here is an example of my code: <select id="country" ng-model="statessource" ng-disabled="!type2" ng-options="country for (country, states) in c ...