使用请求模块下载文件并将结果传递给流星和 node.js 中的响应

download file with request module and pass result to response in meteor and node.js

我想下载文件而不保存在磁盘上并将文件内容传递给响应。真的,我想将文件作为流获取,然后将其传递给响应,客户端可以下载文件。 例如下面的伪代码(iron-router, meteor, request):

Router.route('/file/download', function() {
    var res = this.response;
    var query = this.params.query;
    var id = query.id;

    var request = Meteor.npmRequire('request');
    var future = new (Npm.require('fibers/future'))();

    request('http://myFileHosting.com/files/download?id='+ id, function (error, response, fileContent) {
        if (!error && response.statusCode == 200) {
            future.return(fileContent);
        }
        else
        {
            future.throw(error);
            console.log(error);
        }
    });

    var fileContent = future.wait();

    res.end(fileContent);
}, { where: 'server' });

如何操作?

无需下载到磁盘即可通过文件即时响应的真正解决方案是什么?

试试这个。

Router.route('/file/download', function() {
    var self = this;
    var res = this.response;
    var query = this.params.query;
    var id = query.id;

    var request = Meteor.npmRequire('request');
    var future = new (Npm.require('fibers/future'))();

    request('http://myFileHosting.com/files/download?id='+ id, function (error, response, fileContent) {
        if (!error && response.statusCode == 200) {
            self.response.statusCode = 200;
            self.response.setHeader("Content-Type", response.headers['content-type']);
            self.response.setHeader("Content-disposition", response.headers['content-disposition']);
            self.response.end(fileContent);
            future['return'](true);
        }
        else
        {
            future.throw(error);
            console.log(error);
        }
    });

    return future.wait();
}, { where: 'server' });