# @fastify/throttle 中文文档

规范地址：https://npmcn.com/package/%40fastify/throttle/

版本：3\.0\.4
npm 元数据更新时间：2026-10-18T12:30:54.683Z
中文译文更新时间：2026-11-14T11:30:36.343Z
软件包许可：MIT

本文由上游 README 翻译，可能存在偏差，请结合原文核对 API、命令与配置。版权与许可归原作者所有。

原始 npm 页面：https://www.npmjs.com/package/%40fastify/throttle
原文对照：https://npmcn.com/package/%40fastify/throttle/?lang=original
项目主页：https://github.com/fastify/fastify-throttle#readme
源码仓库：https://github.com/fastify/fastify-throttle

## 关键信息（来自 npm 元数据）

- 包体积（解压后）：60.3 kB，36 个文件
- 模块格式：CommonJS
- TypeScript 类型：包内自带
- 运行依赖：1 个
- 首次发布：2023-08-26T06:46:16.358Z
- 最新版本发布：2026-10-09T08:42:07.381Z
- 近 30 天下载量：2832（2026-10-15 至 2026-11-13，npm 官方下载统计）
- 已发布版本数：9（近 12 个月 2 个）

## 中文简介

固定的喉咙反应

## 安装

```sh
npm install @fastify/throttle
```

也可以使用：`pnpm add @fastify/throttle`、`yarn add @fastify/throttle`、`bun add @fastify/throttle`

## README

# @ fastify/ throttle (法语)

[![CI](https://github.com/fastify/fastify-throttle/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/fastify/fastify-throttle/actions/workflows/ci.yml) [![NPM version](https://img.shields.io/npm/v/@fastify/throttle.svg?style=flat)](https://www.npmjs.com/package/@fastify/throttle) [![neostandard javascript style](https://img.shields.io/badge/code_style-neostandard-brightgreen?style=flat)](https://github.com/neostandard/neostandard)

调高请求的下载速度 .

## 安装

```sh
npm i @fastify/throttle
```

## 使用量

注册插件,并在必要时通过自定义选项.

此插件将添加一个 `onSend` 钩到快取实例,它会拖动响应的下载速度.

```js
import Fastify from 'fastify'

const fastify = Fastify()
await fastify.register(import('@fastify/throttle'), {
  bytesPerSecond: 1024 * 1024, // 1MB/s
  streamPayloads: true, // throttle the payload if it is a stream
  bufferPayloads: true, // throttle the payload if it is a Buffer
  stringPayloads: true // throttle the payload if it is a string
})

fastify.get('/', (request, reply) => {
  reply.send({ hello: 'world' })
})

fastify.listen({ port: 3000 }, err => {
  if (err) {
    throw err
  }
  console.log('Server listening at http://localhost:3000')
})
```

### 选项

在插件注册期间, 您可以通过以下选项 :

```js
await fastify.register(import('@fastify/throttle'), {
  bytesPerSecond: 1000, // 1000 bytes per second
  streamPayloads: true, // throttle the payload if it is a stream
  bufferPayloads: true, // throttle the payload if it is a Buffer
  stringPayloads: true // throttle the payload if it is a string
})
```

您可以将节流全球定义为插件选项或每个路由选项. 每个路由的节流阀选项与插件选项相同.

| 页眉 | 说明 | 默认 |
| --- | --- | --- |
| `bytesPerSecond` | 每秒允许的字节、 数字或函数 | 16384 (英语) |
| `streamPayloads` | 如果有效载荷是溪流的话,就把它压住 | 真实 |
| `bufferPayloads` | 如果有效载荷是缓冲器,则将其吸出 | 虚假 |
| `stringPayloads` | 如果有效载荷是绳子, 则按下 | 虚假 |
| `async` | 如果字节Persecond是返回承诺的函数, 设置为 true | 虚假 |

在全球范围设置节奏的实例:

```js
  const fastify = require('fastify')()

  await fastify.register(import('@fastify/throttle'), {
    bytesPerSecond: 1024 // 1KB/s
  })

  fastify.get('/', (req, reply) => {
    reply.send(createReadStream(resolve(__dirname, __filename)))
  })

  fastify.listen({ port: 3000 })
```

设置每条路线节奏的示例:

```js
  'use strict'

  const fastify = require('fastify')()

  await fastify.register(import('@fastify/throttle'))

  fastify.get('/', {
    config: {
      throttle: {
        bytesPerSecond: 1000
      }
    }
  }, (req, reply) => {
    reply.send(createReadStream(resolve(__dirname, __filename)))
  })

  fastify.listen({ port: 3000 })
```

这个 `bytesPerSecond` 选项可以是数字或函数。 函数用于 `bytesPerSecond` 有以下类型脚本定义 :

```typescript
type BytesPerSecond = (request: FastifyRequest) => ((elapsedTime: number, bytes: number) => number) | Promise<((elapsedTime: number, bytes: number) => number)>
```

`request` 是快捷请求对象.

`elapsedTime` 是流起于几秒后的时间. `bytes` 已经发送的字节.

您必须确保返回值为整数或 `Infinity`。 。 。 .

例如,您可以通过定义 : 页:1 `bytesPerSecond` 像这样:

```js
  const fastify = require('fastify')()

  await fastify.register(import('@fastify/throttle'))

  fastify.get('/', {
    config: {
      throttle: {
        bytesPerSecond: function bytesPerSecondfactory(request) {
          // this function runs for every request
          const client = request.headers['customer-id']

          return function (elapsedTime, bytes) {
            return CONFIG[client] * 2 // return a number of xyz
          }
        }
      }
    }
  }, (req, reply) => {
    reply.send(createReadStream(resolve(__dirname, __filename)))
  })

  fastify.listen({ port: 3000 })
```

这个 `bytesPerSecond` 函数可以是同步函数,也可以是同步函数。 如果您提供了同位素函数, 它会被插件检测到 。 如果是一个同步函数返回承诺, 您必须设置 `async` 选项到 `true`,以便插件知道它应该等待承诺.

```js
  const fastify = require('fastify')()

  await fastify.register(import('@fastify/throttle'))

  fastify.get('/', {
    config: {
      throttle: {
        async: true,
        bytesPerSecond: function bytesPerSecondfactory(request) {
          // this function runs for every request
          const client = request.headers['customer-id']

          return Promise.resolve(function (elapsedTime, bytes) {
            return CONFIG[client] * 2 // return a number of xyz
          })
        }
      }
    }
  }, (req, reply) => {
    reply.send(createReadStream(resolve(__dirname, __filename)))
  })

  fastify.listen({ port: 3000 })
```

## 许可证

**[麻省理工学院](https://github.com/fastify/fastify-throttle/blob/main/LICENSE)**

## 常见问题

### @fastify/throttle 是什么？

固定的喉咙反应

### 如何安装 @fastify/throttle？

在项目目录运行 npm install @fastify/throttle，或使用 pnpm add / yarn add / bun add。

### @fastify/throttle 支持 TypeScript 吗？

支持。包内自带 TypeScript 类型声明（package\.json 声明了 types 入口），安装后即可获得类型提示，无需再安装 @types 包。

### @fastify/throttle 支持 ESM 还是 CommonJS？

以 CommonJS 形式发布，可以直接 require\(\)；在 ES Module 项目中也可以用 import 引入（Node\.js 会把 module\.exports 作为默认导出）。

### @fastify/throttle 可以商用吗？

@fastify/throttle 使用 MIT 许可。宽松许可：允许商业使用、修改和再分发，通常只需在分发时保留原版权与许可声明。以上为概括，不构成法律意见，请以许可原文为准。

### @fastify/throttle 的下载量有多少？

根据 npm 官方下载统计，@fastify/throttle 在 2026/10/15 – 2026/11/13 这 30 天内被下载 2,832 次，日均约 94 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### @fastify/throttle 还在维护吗？

最新版本 3\.0\.4 发布于 2026/10/09（1 个月前）；至今共发布 9 个版本，其中过去 12 个月发布了 2 个；首次发布于 2023/08/26。发布频率只是参考信号：功能稳定的工具可能很少需要更新，建议结合源码仓库的 issue 和提交记录判断。

