使用superagent管道可读流

时间:2016-08-08 20:50:21

标签: node.js multer superagent

我正在尝试创建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...),但显然是endpipe can't both be used together。我觉得我误解了管道是如何工作的,或者我试图做的事情是否切合实际。

1 个答案:

答案 0 :(得分:3)

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

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

您有两种选择:

最简单,效率最低的是:

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

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

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