Pipe superagent response to express response

余生长醉 提交于 2019-12-01 23:25:09

A superagent's response object should not be treated as a stream, because it may already be the result of automatic serialization (e.g. from JSON to a JavaScript object). Rather than using the response object, the documentation on piping data states that you can directly pipe the superagent request to a stream:

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')
})

With Promises, download the following way:

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);
    });
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!