# whatwg-mimetype 中文文档

规范地址：https://npmcn.com/package/whatwg-mimetype/

版本：5\.0\.0
npm 元数据更新时间：2026-01-20T03:04:38.405Z
中文译文更新时间：2026-11-04T23:06:53.838Z
软件包许可：MIT

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

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

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

- 包体积（解压后）：42.6 kB，10 个文件
- 模块格式：CommonJS
- TypeScript 类型：未声明
- Node.js 要求：\>=20
- 运行依赖：0 个
- 首次发布：2017-12-10T06:29:12.340Z
- 最新版本发布：2026-01-20T03:04:38.058Z
- 近 30 天下载量：595202980（2026-10-05 至 2026-11-03，npm 官方下载统计）
- 已发布版本数：8（近 12 个月 1 个）

## 中文简介

根据WHATWG MIME嗅探标准，解析、序列化和操作MIME类型

## 安装

```sh
npm install whatwg-mimetype
```

也可以使用：`pnpm add whatwg-mimetype`、`yarn add whatwg-mimetype`、`bun add whatwg-mimetype`

## README

# 解析、序列化、操作和嗅探MIME类型

这个包将解析 [MIME类型](https://mimesniff.spec.whatwg.org/#understanding-mime-types) 转换成结构化格式，然后可以对其进行操作和序列化：

```js
const { MIMEType } = require("whatwg-mimetype");

const mimeType = new MIMEType(`Text/HTML;Charset="utf-8"`);

console.assert(mimeType.toString() === "text/html;charset=utf-8");

console.assert(mimeType.type === "text");
console.assert(mimeType.subtype === "html");
console.assert(mimeType.essence === "text/html");
console.assert(mimeType.parameters.get("charset") === "utf-8");

mimeType.parameters.set("charset", "windows-1252");
console.assert(mimeType.parameters.get("charset") === "windows-1252");
console.assert(mimeType.toString() === "text/html;charset=windows-1252");

console.assert(mimeType.isHTML() === true);
console.assert(mimeType.isXML() === false);
```

它也可以 [确定资源的MIME类型](https://mimesniff.spec.whatwg.org/#determining-the-computed-mime-type-of-a-resource) 通过嗅它的内容物：

```js
const { computedMIMEType } = require("whatwg-mimetype");

const pngBytes = new Uint8Array([0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);

computedMIMEType(pngBytes).essence;                                    // "image/png"
computedMIMEType(pngBytes, { contentTypeHeader: "image/gif" }).essence // "image/png"
computedMIMEType(pngBytes, { contentTypeHeader: "text/html" }).essence // "text/html"
```

解析、序列化和嗅探都是相当复杂的过程；更多细节请参见规范：

-   [解析](https://mimesniff.spec.whatwg.org/#parsing-a-mime-type)
-   [序列化](https://mimesniff.spec.whatwg.org/#serializing-a-mime-type)
-   [嗅探](https://mimesniff.spec.whatwg.org/#determining-the-computed-mime-type-of-a-resource)

这个包的算法符合WHATWG的算法 [MIME嗅探标准](https://mimesniff.spec.whatwg.org/)，作为… [提交 `e7594d5`](https://github.com/whatwg/mimesniff/commit/e7594d531819053508447f688a3bde465531aca5)。

## api

### `MIMEType`

这个 `MIMEType` 类的构造函数接受一个字符串，它将尝试将其解析为MIME类型；如果解析失败，则返回 `Error` 会被扔。

#### 这个 `parse()` 静态工厂法

作为构造函数的替代方法，您可以使用 `MIMEType.parse(string)`． 唯一的区别是 `parse()` 将返回 `null` 解析失败时，而构造函数将抛出。因此，在不可解析的MIME类型异常的情况下，使用构造函数是最有意义的 `parse()` 当处理来自某些无约束源的输入时。

#### 属性

-   `type`： MIME类型 [类型](https://mimesniff.spec.whatwg.org/#mime-type-type),如。 `"text"`
-   `subtype`： MIME类型 [子类型](https://mimesniff.spec.whatwg.org/#mime-type-subtype),如。 `"html"`
-   `essence`： MIME类型 [本质](https://mimesniff.spec.whatwg.org/#mime-type-essence),如。 `"text/html"`
-   `parameters`的实例 `MIMETypeParameters`，包含此MIME类型 [参数](https://mimesniff.spec.whatwg.org/#mime-type-parameters)

`type` 和 `subtype` 可以改变。它们将被验证为非空且仅包含 [HTTP令牌码点](https://mimesniff.spec.whatwg.org/#http-token-code-point)。

`essence` 只是一个getter，不能被修改。

`parameters` 也是getter，但的内容是 `MIMETypeParameters` 对象是可变的，如下所述。

#### 方法

-   `toString()` 将MIME类型序列化为字符串
-   `isHTML()`：返回true，如果此实例表示 [HTML MIME类型](https://mimesniff.spec.whatwg.org/#html-mime-type)
-   `isXML()`：返回true，如果此实例表示 [XML MIME类型](https://mimesniff.spec.whatwg.org/#xml-mime-type)
-   `isJavaScript({ prohibitParameters })`：返回true，如果此实例表示 [JavaScript MIME类型](https://html.spec.whatwg.org/multipage/scripting.html#javascript-mime-type)。 `prohibitParameters` 可以设置为true以禁用任何参数，即测试MIME类型的序列化是否为 [JavaScript MIME类型本质匹配](https://mimesniff.spec.whatwg.org/#javascript-mime-type-essence-match)。

_注意: `isHTML()`， `isXML()`, `isJavaScript()` 方法是推测性的，可能在未来的主要版本中被删除或更改。看到 [whatwg / mimesniff # 48](https://github.com/whatwg/mimesniff/issues/48) 在这个领域进行头脑风暴。目前我们实现这些主要是因为它们在jdom中很有用。_

### `MIMETypeParameters`

这个 `MIMETypeParameters` 类返回其实例 `mimeType.parameters`的表面API等于a [JavaScript `Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map)。

然而, `MIMETypeParameters` 方法总是将它们的参数解释为适合MIME类型，因此，例如参数名称将是小写的，并且试图设置无效字符将抛出。

一些例子:

```js
const { MIMEType } = require("whatwg-mimetype");

const mimeType = new MIMEType(`x/x;a=b;c=D;E="F"`);

// Logs:
// a b
// c D
// e F
for (const [name, value] of mimeType.parameters) {
  console.log(name, value);
}

console.assert(mimeType.parameters.has("a"));
console.assert(mimeType.parameters.has("A"));
console.assert(mimeType.parameters.get("A") === "b");

mimeType.parameters.set("Q", "X");
console.assert(mimeType.parameters.get("q") === "X");
console.assert(mimeType.toString() === "x/x;a=b;c=d;e=F;q=X");

// Throws:
mimeType.parameters.set("@", "x");
```

### `computedMIMEType()`

这个 `computedMIMEType(resource, options)` 函数确定资源的MIME类型 [MIME类型嗅探算法](https://mimesniff.spec.whatwg.org/#determining-the-computed-mime-type-of-a-resource)． 这包括:

-   供应方式的复杂性 `Content-Type` 头或其他外部信息与嗅探进程交互（但通常不覆盖）；
-   设置“无嗅”标志的能力，就像当 `X-Content-Type-Options: nosniff` 存在，这主要（但不是完全）阻止嗅探；和
-   “Apache bug”检查发生在 `Content-Type` Header是几个特定值之一。

也就是说，这不仅实现了 [用于识别未知MIME类型的规则](https://mimesniff.spec.whatwg.org/#rules-for-identifying-an-unknown-mime-type)． 它为您提供了完整的浏览器兼容MIME嗅探过程所需的一切。

#### 参数

-   **`resource`** （`Uint8Array`)：资源字节。
-   **`options.contentTypeHeader`** （`string`): HTTP资源的Content-Type报头值。
-   **`options.providedType`** （`string`)：来自文件系统或其他协议（如FTP）的MIME类型，用于非http资源。
-   **`options.noSniff`** （`boolean`、默认 `false`)：是否 `X-Content-Type-Options: nosniff` 头出现了。
-   **`options.isSupported`** （`function`、默认 `() => true`)：用 `MIMEType` 实例来检查用户代理是否支持图像/音频/视频MIME类型。如果它返回 `false`对于该类型，嗅探将被跳过。

这个 `contentTypeHeader` 和 `providedType` 选项将被字符串化，因此您也可以提供一个 `MIMEType` (或 [node . js `util` 模块 `MIMEType`](https://nodejs.org/api/util.html#class-utilmimetype)）.

#### 返回值

一个 `MIMEType` 表示计算MIME类型的实例。

## 常见问题

### whatwg-mimetype 是什么？

根据WHATWG MIME嗅探标准，解析、序列化和操作MIME类型

### 如何安装 whatwg-mimetype？

在项目目录运行 npm install whatwg-mimetype，或使用 pnpm add / yarn add / bun add。

### whatwg-mimetype 支持 TypeScript 吗？

该包的 package\.json 没有声明类型入口。需要类型提示时，可以在 npm 上查找社区维护的 @types/whatwg-mimetype 是否存在。

### whatwg-mimetype 支持 ESM 还是 CommonJS？

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

### whatwg-mimetype 需要什么版本的 Node\.js？

package\.json 的 engines 字段要求 Node\.js \>=20。版本不符时 npm 默认只给出警告，开启 engine-strict 后会拒绝安装。

### whatwg-mimetype 可以商用吗？

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

### whatwg-mimetype 的下载量有多少？

根据 npm 官方下载统计，whatwg-mimetype 在 2026/10/05 – 2026/11/03 这 30 天内被下载 595,202,980 次，日均约 19,840,099 次。下载量会把 CI 构建、镜像同步和作为其他包依赖的安装一并计入，适合横向比较热度，不能直接等同于使用人数。

### whatwg-mimetype 还在维护吗？

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

