繁体   English   中英

使用superagent管道可读流

[英]Piping readable stream using 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')
});

我认为这似乎有效,但我不知道如何处理来自superagent POST请求的响应,因为我需要返回从superagent请求收到的令牌。

我已经尝试过post.end(fn...)但显然endpipe 不能同时使用 我觉得我误解了管道是如何工作的,或者我想要做的事情是否切合实际。

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

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

您有两种选择:

最简单,效率最低的是:

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM