Table of contents

Using koa js to respose image, json, xml, or download file

Node.js Feb 27, 2020 Viewed 6.1K Comments 0

With koa, we can return various data types. We need to set the response header content-type. For example, JSON: application/json, XML: application/xml, png: image/png, jpg/jpeg: image/jpeg, and so on. We can use mime-types to guess the data content-type. mime-types  is the ultimate javascript content-type utility. For file stream reading, we can use the fs.createReadStream() method. If the response header does not specify a content-type, the browser may download it as a file.

Example

server.js

const Koa = require('koa');
const app = new Koa();
const mime = require('mime-types')
const fs = require('fs');

app.use(ctx => {
    if (ctx.request.url === '/file') {
        var path = "/Users/apple/Downloads/test.zip";
        var mimeType = mime.lookup(path);
        const src = fs.createReadStream(path);
        ctx.response.set("content-type", mimeType);
        ctx.response.set("content-disposition", "attachment; filename=test.zip");
        ctx.body = src;
    } else if (ctx.request.url === '/image') {
        var path = "/Users/apple/Downloads/201228bli.bmp";
        var mimeType = mime.lookup(path);
        const src = fs.createReadStream(path);
        ctx.response.set("content-type", mimeType);
        ctx.body = src;
    } else if (ctx.request.url === '/json') {
        var jsonType = mime.lookup('json');
        ctx.response.set("content-type", jsonType);
        var json = {text: "Hello, World!"};
        ctx.body =  JSON.stringify(json);
    } else if (ctx.request.url === '/xml') {
        var jsonType = mime.lookup('xml');
        ctx.response.set("content-type", jsonType);
        var html = `
            <xml>
                <user>
                    <name>hello</name>
                </user>
            </xml>
        `;
        ctx.body = html;
    } else {
        ctx.body = "Hello World";
    }
});

app.listen(8000);

Use it

Run the following command to test the sample code.

$ node server.js

Download file: http://localhost:8000/file

Response a image: http://localhost:8000/image

Response json data: http://localhost:8000/json

Response xml data: http://localhost:8000/xml

Response text: http://localhost:8000

Updated Feb 27, 2020