How to buffer an HTTP response using the request module?

前端 未结 4 867
清酒与你
清酒与你 2021-02-01 18:52

I would like to stream the contents of an HTTP response to a variable. My goal is to get an image via request(), and store it in in MongoDB - but the image is alway

4条回答
  •  忘了有多久
    2021-02-01 19:25

    The request module buffers the response for you. In the callback, body is a string (or Buffer).

    You only get a stream back from request if you don't provide a callback; request() returns a Stream.

    See the docs for more detail and examples.


    request assumes that the response is text, so it tries to convert the response body into a sring (regardless of the MIME type). This will corrupt binary data. If you want to get the raw bytes, specify a null encoding.

    request({url:'http://google.com/doodle.png', encoding:null}, function (error, response, body) {
        db.images.insert({ filename: 'google.png', imgData: body}, function (err) {
    
            // handle errors etc.
    
        }); 
    });
    

提交回复
热议问题