1.0.0 • Published 1 year ago

@stream-toolbox/limit v1.0.0

Weekly downloads
-
License
MIT
Repository
github
Last release
1 year ago

@stream-toolbox/limit

English 中文文档


⏳ Create a duplex that limits streaming transfer rate.

Installation

npm i @stream-toolbox/limit

Quick Start

Control file copy speed:

const createLimit = require("@stream-toolbox/limit");
const { createReadStream, createWriteStream } = require("fs");

const readable = createReadStream("foo.mp4");
const duplex = createLimit(1048576); // 1048576 bytes per second (1MB/s)
const writable = createWriteStream("foo_copy.mp4");

readable.pipe(duplex).pipe(writable);

Control the upload bandwidth of a single HTTP request:

const http = require("http");
const createLimit = require("@stream-toolbox/limit");

http
  .createServer((req, res) => {
    if (req.url === "/") {
      res.setHeader("content-type", "text/html; charset=utf-8");
      res.end(`<form action="/upload" method="post" enctype="multipart/form-data"><input name="file" type="file" multiple /><button type="submit">submit</button></form>
    `);
    } else {
      const start = process.uptime();
      const chunks = [];
      req
        .pipe(createLimit(8 * 1024)) // 8 KB/s
        .on("data", (chunk) => {
          chunks.push(chunk);
        })
        .on("end", () => {
          const reqBody = Buffer.concat(chunks);
          res.end(`Uploaded ${reqBody.length} bytes size of data in ${process.uptime() - start} seconds`);
        });
    }
  })
  .listen(8080);

API

createLimit(bytesPerSecond: number): Duplex

⏳ 创建一个双工流用于控制流的传输速度。

安装

npm i @stream-toolbox/limit

快速开始

控制文件拷贝速度:

const createLimit = require("@stream-toolbox/limit");
const { createReadStream, createWriteStream } = require("fs");

const readable = createReadStream("foo.mp4");
const duplex = createLimit(1048576); // 每秒 1048576 字节 (1MB/s)
const writable = createWriteStream("foo_copy.mp4");

readable.pipe(duplex).pipe(writable);

控制单个 HTTP 请求的上行带宽:

const http = require("http");
const createLimit = require("@stream-toolbox/limit");

http
  .createServer((req, res) => {
    if (req.url === "/") {
      res.setHeader("content-type", "text/html; charset=utf-8");
      res.end(`<form action="/upload" method="post" enctype="multipart/form-data"><input name="file" type="file" multiple /><button type="submit">submit</button></form>
    `);
    } else {
      const start = process.uptime();
      const chunks = [];
      req
        .pipe(createLimit(8 * 1024)) // 8 KB/s
        .on("data", (chunk) => {
          chunks.push(chunk);
        })
        .on("end", () => {
          const reqBody = Buffer.concat(chunks);
          res.end(`Uploaded ${reqBody.length} bytes size of data in ${process.uptime() - start} seconds`);
        });
    }
  })
  .listen(8080);

API

createLimit(bytesPerSecond: number): Duplex