nodejs管道https响应request.post和写入文件

时间:2017-08-30 08:47:37

标签: node.js http stream request pipe

我正在制作检查http url的http代理程序,如果是下载链接(内容类型:octet-stream),我会得到响应并通过使用request.post和其他计算机下载文件将该响应转发给其他计算机响应由http代理提供。

假设网络代理计算机是A.并且它是A的代码的一部分.192.168.5.253

    if(contentType && (contentType== "application/octet-stream" || contentType == "application/gzip")){
                console.log("remoteRes##app",remoteRes);
                let filepath = req.url.split('/');
                let FileName = getFilename(remoteRes, filepath);
                let writeStream = fs.createWriteStream(FileName);


    /*remoteRes is octect-stream response. 
      I can get file buffer If I use remoteRes.on(data, chunk => {...})*/
                remoteRes.pipe(writeStream); //It works but I want to send file buffer to B without writing file.
 .........

我可以在A中下载文件,但我想将此响应发送到pc B(192.168.5.32:10001)服务器。 所以我想像这样流式传输:

remoteRes.pipe(request.post('http://192.168.5.32:10001/upload));

这是服务器B(192.168.5.32)代码的一部分

router.post('/upload', (req, res, next) => {


  let wstream = fs.createWriteStream('ffff.txt');

  req.pipe(wstream); //It dosen't work, but I want to do like this. 

})

我想在router.post(' / upload')中获取filebuffer。如果它是邮寄或放置,那就无所谓了。 当我使用remoteRes.pipe(request.post(' http://192.168.5.32:10001/upload))时,我看到了 ,我看到ServerA的请求到达ServerB。但我无法在ServerB中获取文件缓冲区。 简而言之,我想管道对request.post的响应。

1 个答案:

答案 0 :(得分:1)

您需要使用自己的中间件存储传入的缓冲区,因此它将在路由器请求处理程序中可用

这里有一个工作示例(您可以保存并将其作为单个文件进行测试):

//[SERVER B]
const express = require('express'); const app = express()
//:Middleware for the incoming stream
app.use(function(req, res, next) {
  console.log("[request middleware] (buffer storing)")
  req.rawBody = ''
  req.on('data', function(chunk) {
    req.rawBody += chunk
    console.log(chunk) // here you got the incoming buffers
  })
  req.on('end', function(){next()})
});
//:Final stream handling inside the request
app.post('/*', function (req, res) {
 /* here you got the complete stream */
 console.log("[request.rawBody]\n",req.rawBody)
});
app.listen(3000)

//[SERVER A]
const request = require('request')
request('http://google.com/doodle.png').pipe(request.post('http://localhost:3000/'))

我希望您能根据具体用例推断出这一点。