Search code examples
javascriptnode.jsmeteoriron-router

Iron router on action using Meteor.call throws writeHead is not a function


I'm trying to write a buffer which returns from server to the client response.

Therefore, I've defined a route which runs to fetch file on action function:

Router.route('/download/:blabla', {
    name: 'download',
    action: function () {
       var that = this.response;
       Meteor.call('downloadFile', blabla, function (err, result) {
           // error check etc.
           var headers = {
               'Content-type' : 'application/octet-stream',
               'Content-Disposition' : 'attachment; filename=' + fileName
           };
           that.writeHead(200, headers);
           that.end(result);
        }
    }
});

This throws:

Exception in delivering result of invoking 'downloadFile': TypeError: that.writeHead is not a function

Without Metoer.call it works...

I'm using nodejs stream to fetch buffer on server side function and it works.

Thanks in advance


Solution

  • Have you tried using a server side only route in IR? i.e. make the route accessible on the server only with `{where:"server"}' to avoid having to do a method call as per example below from here (note serving the file int his example requires the addition of the meteorhacks:npm package as per comments but you might be able to avoid this...):

    Router.route("/file/:fileName", function() {
      var fileName = this.params.fileName;
    
      // Read from a file (requires 'meteor add meteorhacks:npm')
      var filePath = "/path/to/pdf/store/" + fileName;
      var fs = Meteor.npmRequire('fs');
      var data = fs.readFileSync(filePath);
    
      this.response.writeHead(200, {
        "Content-Type": "application/pdf",
        "Content-Length": data.length
      });
      this.response.write(data);
      this.response.end();
    }, {
      where: "server"
    });