How to create and download a text file in Meteor?

508 views Asked by At

How can I create a text file easily in Meteor (Server Side) and download as a .txt file?

// On Server
if (Meteor.isServer) {
  Meteor.methods({
    'scan-db': function () {
       // scan the DB for corrupted data
       var allEntries = Jobs.find().fetch();
       var report = "";
       for ( let i = 0; i < allEntries.length ; i ++ ) {
         if ( validate(allEntries[i]) == false ) {
           report = report + allEntries[i].entryNumber + " has a problem" + "\n";
         // used \n for line breaks in windows
         }
       return report; // a whole bunch of string

  })
}


// On client
if (Meteor.isClient) {
  Meteor.call("scan-db", function(err, res) {
     if (res) {
        downloadFile(res);
     }
  })
}

I am hoping to be able to download my result as a text file to save. Is there any easy way of doing this? I tried using meteorhacks:picker but apparently the package is not working or Picker returned undefined despite importing it import { Picker } from 'meteor/meteorhacks:picker';

1

There are 1 answers

2
remeus On

If you want to return it through a Meteor method, the easiest solution is to return the text content and then generate the file on the client.

You can create a Blob and use a library such as FileSaver to start the download. If you don't want to use any library, a common hack is to generate an html link to the blob file, append it to the DOM and trigger a click on it.