Skip to content

Instantly share code, notes, and snippets.

@spiechu
Last active January 1, 2017 22:22
Show Gist options
  • Save spiechu/c7beac6f638323111966012c4320daaa to your computer and use it in GitHub Desktop.
Save spiechu/c7beac6f638323111966012c4320daaa to your computer and use it in GitHub Desktop.
const express = require('express');
const app = express();
// define app logging, middleware, view engine etc.
// make sure you
// npm install advanced-throttle --save
const Throttle = require('advanced-throttle');
// boring factory...
const createThrottle = function () {
// max transfer 5000 bytes / second
return new Throttle(5000);
};
// we're going to serve files on '/public' dir
const serveStatic = express.static(path.join(__dirname, 'public'), {});
// typical Express middleware
app.use('/public', function (req, res, next) {
// stream emits 'pipe' event when piped
res.on('pipe', function (readStream) {
// protects against infinite loop
if (readStream instanceof Throttle) {
return;
}
// first unpipe streams
readStream.unpipe(res);
// then reattach with Transform type between streams
// Throttle class extends require('stream').Transform
readStream.pipe(createThrottle()).pipe(res);
});
// start serving files
serveStatic(req, res, next);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment