[英]Piping readable stream using superagent
I'm trying to create a multer middleware to pipe a streamed file from the client, to a 3rd party via 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')
});
I think this seems to work, but I'm not sure how to handle the response from superagent POST
request, since I need to return a token received from the superagent request. 我认为这似乎有效,但我不知道如何处理来自superagent
POST
请求的响应,因为我需要返回从superagent请求收到的令牌。
I've tried post.end(fn...)
but apparently end
and pipe
can't both be used together . 我已经尝试过
post.end(fn...)
但显然end
和pipe
不能同时使用 。 I feel like I'm misunderstanding how piping works, or if what i'm trying to do is practical. 我觉得我误解了管道是如何工作的,或者我想要做的事情是否切合实际。
Superagent's .pipe()
method is for downloading (piping data from a remote host to the local application). Superagent的
.pipe()
方法用于下载(将数据从远程主机传输到本地应用程序)。
It seems you need piping in the other direction: upload from your application to a remote server. 您似乎需要在另一个方向上进行管道传输:从应用程序上传到远程服务器。 In superagent (as of v2.1) there's no method for that, and it requires a different approach.
在superagent(从v2.1开始)没有方法,它需要一种不同的方法。
You have two options: 您有两种选择:
The easiest, less efficient one is: 最简单,效率最低的是:
Tell multer to buffer/save the file, and then upload the whole file using .attach()
. 告诉multer缓冲/保存文件,然后使用
.attach()
上传整个文件。
The harder one is to "pipe" the file "manually": 更难的是“手动”“管道”文件:
data
events on the incoming file stream, and call superagent's .write()
method with each chunk of data. data
事件,并使用每个数据块调用superagent的.write()
方法。 end
event on the incoming file stream, and call superagent's .end()
method to read server's response. end
事件,并调用superagent的.end()
方法来读取服务器的响应。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.