koa.js streaming response from remote url
Asked Answered
S

1

7

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.

Schroer answered 21/1, 2016 at 9:4 Comment(2)
You were on the right track, but you just need to set this.body to a readable stream. Your answer (with the request module) works because req(url) returns a readable stream. In general, when you want to work with streams directly in Koa/co, you aren't going to be using yield.Bewitch
@Bewitch that makes sense.Schroer
S
8

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.

Schroer answered 21/1, 2016 at 9:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.