I understood! However, this required several additional packages. First, let me describe the workflow in more detail:
A user on our site searches. On the next page of search results, there is a button that allows the user to export their search results to a CSV file. Then the file will be exported to the browser for download.
One of the problems we had was that the file is written to the server, making sure that only the user who exports the file has the ability to view the file. To control who was visible in the files, I used the CollectionFS meteorite packet (mrt add collectionFS or clone from github ). This package writes file buffers to the mongo collection. Delivering the owner field when you save gives you control over access.
No matter how the file is created, whether it is saved on the server using the upload form or generated on the fly, as I did using the json2csv package, the file must be streamed in CollectionFS as a buffer.
var userId = Meteor.userId() var buffer = Buffer(csv.length); //csv is a var holding the data for write var filename = "name_of_file.csv"; for ( var i=0; i<csv.length; i++ ) { buffer[i] = csv.charCodeAt(i); } CollectionFS.storeBuffer(filename, buffer, { contentType: 'text/plain', owner: userId });
So, at this point, I took the data file and passed it as a buffer to the mongo collection. Since my data exists in memory in var csv, I pass it as a buffer by looping through each character. If it was a file saved on a physical disk, I would use fs.readFileSync (file) and send the returned buffer to CollectionFS.storeBuffer ().
Now that the file is saved as a buffer in mongo with the owner, I can restrict access to it. I am publishing a CollectionFS collection that can upload / update / delete a file or even know that a file exists.
To read the file from mongo and send the file to the browser for download, you need another Javascript library: FileSaver ( github ).
Using the retrieveBlob method from CollectionFS, pull your file out of mongo as a blob by providing a _id that references the file in your mongo collection. FileSaver has a method, saveAs, which accepts a blob and exports to the browser for download as the specified file name.
var file = // file object stored in meteor CollectionFS.retrieveBlob(file._id, function(fileItem) { if ( fileItem.blob ) saveAs(fileItem.blob, file.filename); else if ( fileItem.file ) saveAs(fileItem.file, file.filename); });
I hope someone finds this useful!