← 中文资源

简体中文版本

MIMEType 解析媒体类型参数

用 MIMEType 类解析媒体类型字符串:type、subtype、essence 一目了然,参数作为 MIMEParams 映射可读取、遍历、修改并重新序列化。

阅读英文原文

运行结果

以下输出由构建管线在沙箱中真实运行该示例捕获。

type: text
subtype: html
essence: text/html
charset: utf-8
param: charset = utf-8
param: boundary = gc0p4Jq0M
has boundary: true
re-serialized: text/html;charset=utf-16

实现说明

迭代发生在 for (const [name, value] of mime.params) 内部——循环之外的语句只执行一遍。node:util 提供 MIMEType——内建表面,不涉及任何包。 mime 定义在模块顶层,中间不经过函数作用域。

使用要点

  • 依赖面只有 node:util,而它内置于 Node.js。
  • 直接运行文件,输出会带上标签,比如 type:、subtype:、essence:——输出的每一行都能指回产生它的那次调用。

常见问题

它从项目之外导入了什么?

只有 node:util,而它是 Node.js 内建的——随运行时提供。

核心语句

const mime = new MIMEType('text/html; charset=utf-8; boundary=gc0p4Jq0M');
mime.params.set('charset', 'utf-16');
mime.params.delete('boundary');

代码示例

import { MIMEType } from 'node:util';

// MIMEType parses a media type string into type, subtype, and parameters
const mime = new MIMEType('text/html; charset=utf-8; boundary=gc0p4Jq0M');

console.log('type:', mime.type);
console.log('subtype:', mime.subtype);
console.log('essence:', mime.essence);
console.log('charset:', mime.params.get('charset'));

// params is a MIMEParams map: iterate, test, and mutate it
for (const [name, value] of mime.params) {
  console.log('param:', name, '=', value);
}
console.log('has boundary:', mime.params.has('boundary'));

mime.params.set('charset', 'utf-16');
mime.params.delete('boundary');
console.log('re-serialized:', mime.toString());