实现说明
迭代发生在 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());