Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
578 views
in Technique[技术] by (71.8m points)

javascript - Koa2 - How to write to response stream?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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", "txt/html");
        ctx.body = src;
    } else {
        // normal KOA response
        ctx.body = 'BODY: Hello, World!' ;
    }
});

app.listen(8080);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...