【问题标题】:Piping readable stream using superagent使用超级代理管道可读流
【发布时间】:2016-08-09 07:27:30
【问题描述】:

我正在尝试创建一个multer 中间件,以通过superagent 将来自客户端的流式文件传输到第三方。

const superagent = require('superagent');
const multer = require('multer');

// my middleware
function streamstorage(){
    function StreamStorage(){}

    StreamStorage.prototype._handleFile = function(req, file, cb){
        console.log(file.stream)  // <-- is readable stream
        const post = superagent.post('www.some-other-host.com');

        file.stream.pipe(file.stream);

        // need to call cb(null, {some: data}); but how
        // do i get/handle the response from this post request?
    }
    return new StreamStorage()
}

const streamMiddleware = {
    storage: streamstorage()
}

app.post('/someupload', streamMiddleware.single('rawimage'), function(req, res){
    res.send('some token based on the superagent response')
});

我认为这似乎可行,但我不确定如何处理来自超级代理 POST 请求的响应,因为我需要返回从超级代理请求接收到的令牌。

我试过post.end(fn...) 但显然end 和pipe can't both be used together。我觉得我误解了管道的工作原理,或者我正在尝试做的事情是否实用。

【问题讨论】:

    标签: node.js multer superagent


    【解决方案1】:

    Superagent 的.pipe() 方法用于下载(将数据从远程主机传输到本地应用程序)。

    您似乎需要从另一个方向进行管道:从您的应用程序上传到远程服务器。在 superagent(从 v2.1 开始)中没有这种方法,它需要不同的方法。

    你有两个选择:

    最简单但效率较低的方法是:

    告诉 multer 缓冲/保存文件,然后使用 .attach() 上传整个文件。

    更难的是“手动”“管道”文件:

    1. 使用您要上传的 URL、方法和 HTTP 标头创建一个超级代理实例,
    2. 监听传入文件流上的data事件,并对每个数据块调用superagent的.write()方法。
    3. 监听传入文件流的end事件,调用superagent的.end()方法读取服务器响应。

    【讨论】:

    • 这是有道理的。我目前正在做第一个建议,所以我会尝试第二个解决方案。
    猜你喜欢
    • 2017-07-07
    • 2016-11-23
    • 2017-08-25
    • 1970-01-01
    • 2021-03-03
    • 2016-02-17
    • 2017-03-22
    • 2021-11-06
    • 1970-01-01
    相关资源
    最近更新 更多