将superagent响应传输到express响应

3
我正在尝试使用express应用程序“代理”某些文件。为什么下面的代码不起作用?
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]

当我调用我的端点时,它永远不会完成。
$ 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
2个回答

3
一个 superagent 的响应对象不应该被视为一个流,因为它可能已经是自动序列化的结果(例如从 JSON 到 JavaScript 对象)。而不是使用响应对象,管道数据文档指出可以直接将 superagent 请求传输到流中。
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
1
@kharandziuk 看起来这取决于具体实现。根据源代码,在Node.js中,Response对象确实是一个ReadableStream,但这是一个私有API,不应该在外部使用。无论如何,文档中没有显示响应对象可以用作可读流。 - E net4
1
如果你仍然想知道_res.pipe之后会发生什么,这里有一个很好的评论:https://github.com/visionmedia/superagent/issues/684#issuecomment-233959045 - E net4

-1
使用 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);
    });
};

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接