12

Using Koa2 and I'm not sure how to write data to the response stream, so in Express it would be something like:

res.write('some string');

I understand that I can assign a stream to ctx.body but I'm not familiar with node.js streams too well so don't know how I would go about creating this stream.

user3690467
  • 3,049
  • 6
  • 27
  • 54

1 Answers1

12

The koa documentation allows you to assign a stream to your response: (from https://koajs.com/#response)

ctx.response.body=

Set response body to one of the following:

  • string written
  • Buffer written
  • Stream piped
  • Object || Array json-stringified
  • null no content response

ctx.body is just a shortcut to ctx.response.body

So here are some examples how you could use it (plus standard koa body assignment)

Calling the server with

  • localhost:8080/stream ... will respond with the data stream
  • localhost:8080/file ... will respond with the file stream
  • localhost:8080/ ... just sends back standard body
'use strict';
const koa = require('koa');
const fs = require('fs');

const app = new koa();

const readable = require('stream').Readable
const s = new readable;

// response
app.use(ctx => {
    if (ctx.request.url === '/stream') {
        // stream data
        s.push('STREAM: Hello, World!');
        s.push(null); // indicates end of the stream
        ctx.body = s;
    } else if (ctx.request.url === '/file') {
        // stream file
        const src = fs.createReadStream('./big.file');
        ctx.response.set("content-type", "text/html");
        ctx.body = src;
    } else {
        // normal KOA response
        ctx.body = 'BODY: Hello, World!' ;
    }
});

app.listen(8080);
Sebastian Hildebrandt
  • 2,661
  • 1
  • 14
  • 20
  • @AbhishekAnand Tested it right now once again ... works fine. If you call the server with localhost:8080/file, of course you need to make sure, that you have a file (named 'big.file' in this example) in your app directory. If you have problems, please be more specific and provide the error message you got. – Sebastian Hildebrandt Nov 12 '19 at 16:43
  • 4
    it says '_read() is not implemented on Readable stream'. Fixed it with new readable({ read(size) { } }); – Abhishek Anand Nov 13 '19 at 05:37
  • The correct Content-Type for HTML is `text/html`, not `txt/html`. – Nina Lisitsinskaya Dec 26 '21 at 06:02
  • @NinaLisitsinskaya yes, you are absolutely right! I corrected it in the original post. Thank you! – Sebastian Hildebrandt Dec 27 '21 at 09:11