Browse files

Initial commit...

  • Loading branch information...
0 parents commit bce763eca62ed994844df6c9f90ba478b481e1f8 @TooTallNate committed Jan 24, 2011
Showing with 75 additions and 0 deletions.
  1. +27 −0 README.md
  2. +14 −0 package.json
  3. +34 −0 throttle.js
27 README.md
@@ -0,0 +1,27 @@
+node-throttle
+=============
+### Throttle node Stream instances with "Bytes per Second".
+
+This micro-module offers a `throttle(bytesPerSecond)` Function, which is compatible
+with [node][NodeJS] `Stream` instances. It can be useful for throttling HTTP uploads
+or to simulate reading from a file in real-time, etc.
+
+
+Usage
+-----
+
+ var throttle = require('throttle'); // Extends `Stream.prototype`
+
+ var bytesPerKilobyte = 1024;
+ throttle(process.stdin, 100 * bytesPerKilobyte);
+
+ // "data" events from 'stdin' will only arrive at a rate of 100kbps...
+
+
+Installation
+------------
+
+ npm install throttle
+
+
+[NodeJS]: http://nodejs.org
14 package.json
@@ -0,0 +1,14 @@
+{
+ "name": "throttle",
+ "description": "Throttle node Stream instances with \"bytes per second\".",
+ "version": "0.0.1",
+ "repository": "git://github.com/TooTallNate/node-throttle.git",
+ "author": "Nathan Rajlich <nathan@tootallnate.net>",
+ "main": "./throttle",
+ "scripts": {
+ "test": "expresso test/test*.js"
+ },
+ "engines": {
+ "node": "*"
+ }
+}
34 throttle.js
@@ -0,0 +1,34 @@
+module.exports = function throttle(stream, bytesPerSecond) {
+
+ var startTime = Date.now();
+ var totalBytes = 0;
+ var timeoutId;
+
+ stream.on("data", onData);
+
+ function resume() {
+ timeoutId = undefined;
+ stream.resume();
+ }
+
+ function onData(chunk) {
+ totalBytes += chunk.length;
+ var totalSeconds = (Date.now() - startTime) / 1000;
+ var expected = totalSeconds * bytesPerSecond;
+ if (totalBytes > expected) {
+ // Use this byte count to calculate how many seconds ahead we are.
+ var remainder = totalBytes - expected;
+ var sleepTime = remainder / bytesPerSecond * 1000;
+ //if (sleepTime > 40) {
+ stream.pause();
+ timeoutId = setTimeout(resume, sleepTime);
+ //}
+ }
+ }
+
+ // The return value is a Function that, when invoked, will cancel the throttling behavior
+ return function unthrottle() {
+ if (timeoutId) clearTimeout(timeoutId);
+ stream.removeListener('data', onData);
+ }
+}

0 comments on commit bce763e

Please sign in to comment.