Introduction
HTTPアップロード/ダウンロードのスロットリングや、
ファイルからの読み込みをリアルタイムでシミュレートする場合など
速度制限をかけたいケースがあります。
そんな機能を簡単に実装するモジュールがnode-throttleです。
※けっこう昔のモジュールですが、問題なく動きました
ThrottleモジュールはThrottle passthrough streamクラスを提供します。
このクラスを使うことにより、1秒あたり通信可能なバイト数を指定することができます。
Environment
今回試した環境は以下のとおりです。
- MacBook Pro (13-inch, M1, 2020)
- OS : MacOS 13.5.2
- Node : v18.15.0
Try
ではthrottleを使ってみましょう。
node-throttleモジュールをインストールします。
% npm install throttle
throttleをつかって、ダウンロード速度を50kbpsに制限して
ダウンロードするサンプルです。
//main.js
const fs = require('fs');
const http = require('http');
const throttle = require('throttle');
const filePath = 'path/your/download_file';
const downloadSpeed = 50 * 1024; // 50kbps
http.createServer((req, res) => {
const fileStream = fs.createReadStream(filePath);
const throttleStream = new throttle(downloadSpeed);
//fileStream.pipe(res);
fileStream.pipe(throttleStream).pipe(res);
}).listen(8000);
ダウンロード用ファイルを用意し、
main.jsを起動してlocalhost:8000にアクセスしてみてください。
ダウンロード速度は指定したとおりになっています。
% node main.js