使用超级代理管道可读流

Piping readable stream using superagent

我正在尝试创建 multer middleware to pipe a streamed file from the client, to a 3rd party via 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 请求的响应,因为我需要 return 从超级代理请求收到的令牌。

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

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

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

你有两个选择:

最简单但效率较低的一种是:

告诉 multer buffer/save 文件,然后使用 .attach().

上传整个文件

更难的是 "pipe" 文件 "manually":

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