Last active
January 1, 2017 22:22
-
-
Save spiechu/c7beac6f638323111966012c4320daaa to your computer and use it in GitHub Desktop.
Code for blog post at http://spiechu.pl/2017/01/01/serving-throttled-static-files-in-nodejs-express/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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