Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

koa.js streaming response from remote url

I want to create a koa route that acts like a proxy for another url, which delivers a file that is usually a few dozens of Megabytes.

Therefore I would like not to block when making the response. I am using this.body = yield request.get(url); currently, where request is the [co-request]1 module.

How do I stream the response back to the client ?

Edit :

I am now doing the following :

var req = require('request');
//...
this.body = req(url).pipe(fs.createWriteStream(this.params.what));

If I paste the url in my browser, I get a file just fine. However if I get a Error: Cannot pipe. Not readable. in my route.

like image 969
nha Avatar asked Jan 21 '16 09:01

nha


1 Answers

Turns out the solution was simply :

var req = require('request');
//...
this.body = req(url);

This is because this.body has to be a readable stream, which req(url) returns. Thanks to @danneu for the explanation.

like image 123
nha Avatar answered Nov 04 '22 02:11

nha