首页 > 解决方案 > 快递限制上传速度

问题描述

是否可以限制文件的快速上传速度?

示例:用户有 10Mbp/s 的互联网,我想限制然后只上传他互联网速度的 1/10。

我试图使用模块节流阀,因为这篇文章说https://stackoverflow.com/a/32340972/13539397但似乎不起作用。

我的代码:

const Throttle = require("throttle");

route.put("/api/upload", (req, res, next) => {
    req.pipe(new Throttle(1)).pipe(fs.createWriteStream(join(__dirname, "./file.png")));
})

标签: javascriptfileexpressupload

解决方案


express-throttle-bandwidth改用包

var express = require('express')
var throttle = require('express-throttle-bandwidth');
var app = express()
app.use(throttle(100000)); // limits to 100000 bps

app.put("/api/upload", (req, res, next) => {
    req.pipe(fs.createWriteStream(join(__dirname, "./file.png"));
})

由于这限制了实例的连接,所以仅将此实例用于文件上传

你也可以使用express-throttle

var express = require("express");
var throttle = require("express-throttle");
  
var app = express();
  
// Allow 5 requests at any rate with an average rate of 5/s
app.put("/api/upload",throttle({ "rate": "5/s" }), (req, res, next) => {
    req.pipe(fs.createWriteStream(join(__dirname, "./file.png"));
})

推荐阅读