Pipe superagent response to express response

前端 未结 2 384
故里飘歌
故里飘歌 2021-01-20 14:52

I\'m trying to \"proxy\" some file with an express app. Why the code below doesn\'t work?

var app = require(\'express\')()
var request = require(\'superagent         


        
相关标签:
2条回答
  • 2021-01-20 15:29

    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')
    })
    
    0 讨论(0)
  • 2021-01-20 15:38

    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);
        });
    };
    
    0 讨论(0)
提交回复
热议问题