@noonesstudios/koa-stream

1.0.0 • Public • Published

Sends chunks of a resource utilizing the Range headers on client's request, otherwise streams it.

Inspired By

koa-stream

Install

npm install @noonesstudios/koa-stream

Implementation

// routes.js

const Router = require('koa-router');
const router = new Router();
const path = require('path');
router.stream = require('@noonesstudios/koa-stream');

router.get('/', ctx => ctx.body = 'Hello');
router.stream('/uploads/:fileName', {
    resourceDirPath: path.resolve(__dirname, 'uploads'), // required, elaborated below
    errorHandler: function (err, ctx) {...}, // optional
    middlewares: [middleware1, middleware2, ...etc] // optional
});

module.exports = router;

API

  • resourceDirPath can be set dynamically using a middleware: erase the line from config and append KOA_STREAM_DIR_PATH to ctx.

example:

function middleware1 (ctx, next) {
    ctx.KOA_STREAM_DIR_PATH = path.resolve(__dirname, 'uploads', ctx.state.user.id);
    return next();
}
  • Name of the file is parsed either by setting the param :fileName as part of the url, or by reading ctx.KOA_STREAM_FILE_NAME if :fileName is not set

example:

function middleware1 (ctx, next) {
    ctx.KOA_STREAM_FILE_NAME = 'myFileName.mp3'
    return next();
}
  • Error handling: errors are thrown up the chain unless you pass your own error handling function. (err, ctx) will be attached

More sources

Future

Depends on requests if any

Package Sidebar

Install

npm i @noonesstudios/koa-stream

Weekly Downloads

0

Version

1.0.0

License

ISC

Unpacked Size

4.82 kB

Total Files

4

Last publish

Collaborators

  • noonesstudios