【问题标题】:Pipe superagent response to express response管道超级代理响应以表达响应
【发布时间】:2016-11-23 11:59:41
【问题描述】:

我正在尝试使用快速应用程序“代理”某些文件。为什么下面的代码不起作用?

var app = require('express')()
var request = require('superagent')
app.get('/image', function(req, res, next) {
  request('http://s3.amazonaws.com/thumbnails.illustrationsource.com/huge.104.520060.JPG')
    .then(function(_res) {
      _res.pipe(res)
    })
})

app.listen(3001, function() {
  console.log('listen')
})

当我直接“wget”一个文件时,它可以工作:

$ wget http://s3.amazonaws.com/thumbnails.illustrationsource.com/huge.104.520060.JPG
--2016-07-20 11:44:33--  http://s3.amazonaws.com/thumbnails.illustrationsource.com/huge.104.520060.JPG
Resolving s3.amazonaws.com... 54.231.120.106
Connecting to s3.amazonaws.com|54.231.120.106|:80... connected.
HTTP request sent, awaiting response... 200 OK
Length: 21026 (21K) [image/jpeg]
Saving to: 'huge.104.520060.JPG'

huge.104.520060.JPG                           100%[==============================================================================================>]  20.53K  --.-KB/s    in 0.1s

2016-07-20 11:44:34 (203 KB/s) - 'huge.104.520060.JPG' saved [21026/21026]

当我调用我的 enpdpoint 时,它永远不会结束:

$ wget localhost:3001/image
--2016-07-20 11:45:00--  http://localhost:3001/image
Resolving localhost... 127.0.0.1, ::1
Connecting to localhost|127.0.0.1|:3001... connected.
HTTP request sent, awaiting response...

一些细节:

$ npm -v
3.9.5

$ npm list --depth=0
express-superagent-pipe-file
├── express@4.14.0
└── superagent@2.1.0

【问题讨论】:

    标签: node.js express superagent


    【解决方案1】:

    不应将超级代理的响应对象视为流,因为它可能已经是自动序列化的结果(例如从 JSON 到 JavaScript 对象)。 documentation on piping data 声明您可以直接将超级代理请求通过管道传输到流,而不是使用响应对象:

    var app = require('express')()
    var request = require('superagent')
    app.get('/image', function(req, res, next) {
      request('http://s3.amazonaws.com/thumbnails.illustrationsource.com/huge.104.520060.JPG')
        .pipe(res)
    })
    
    app.listen(3001, function() {
      console.log('listen')
    })
    

    【讨论】:

    • 谢谢!有用。但是_res.pipe函数在这种情况下有什么作用呢?
    • @kharandziuk 它似乎依赖于实现。根据the source codeResponse 对象确实是 Node.js 中的ReadableStream,但它是不应该在外部使用的私有 API。文档中没有任何内容表明响应对象无论如何都可以用作可读流。
    • 如果您仍然想知道_res.pipe 之后会发生什么,这里有一个很好的评论:github.com/visionmedia/superagent/issues/…
    【解决方案2】:

    使用 Promises,下载方式如下:

    const fs = require('fs');
    const path = require('path');
    
    const download = (url) => {
        return superagent.get(url)
        .then((response) => {
            const stream = fs.createWriteStream('file.ext');
            return response.pipe(stream);
        });
    };
    

    【讨论】:

      猜你喜欢
      • 2018-04-09
      • 1970-01-01
      • 1970-01-01
      • 2014-09-21
      • 1970-01-01
      • 2019-07-25
      • 1970-01-01
      • 2014-07-08
      • 2014-03-12
      相关资源
      最近更新 更多