Sends chunks of a resource utilizing the Range
headers on client's request,
otherwise streams it.
Inspired By
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 appendKOA_STREAM_DIR_PATH
toctx
.
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 readingctx.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