当前位置:网站首页>nodeJs--mime模块
nodeJs--mime模块
2022-08-02 00:05:00 【H5_ljy】
一、mime模块是什么
mime是一个互联网标准,通过设定它就可以设定文件在浏览器的打开方式。
它是第三方模块,需要手动下载。
二、如何安装mime模块
使用npm安装模块
npm -i mime //下载到全局则要加-g

安装完后项目中会出现node_modules和json文件说明安装成功;接下来就可以使用require来引入它了
三、mime模块方法
1.mime.getType(url)
可以通过路径返回资源类型
可以给网站请求的资源(html、css等)添加一个content-type
没有添加content-type使用高级浏览器不会出错,但低级浏览器可能会出错
var http = require('http')
var url = require('url')
var mime = require('mime')
var fs = require('fs')
http.createServer((req, res) => {
let pathname = url.parse(req.url).pathname
let type = mime.getType(req.url)
console.log(type)
fs.readFile(__dirname + pathname, (err, data) => {
if (!err) {
res.setHeader("content-Type", type)
res.end(data)
}
})
}).listen(8081)
当我访问test.txt文档时
2.mime.getExtension(type)
查询文件护展名可配合getType使用,传入的是MIME类型
var mime = require('mime')
var type=mime.getType("./img/test.txt")
let type2=mime.getExtension(type)
console.log(type,type2)

3.mime.define
mime自定义类型,当mime模块自带的mime-db库不存在或不能满足我们所需的MIME类型时,还可以自定义MIME类型
var mime = require('mime')
mime.define({
'text/mytext': ['t-txt', 't-ext', 't-xt'],
});
type=mime.getExtension('text/mytext')
console.log(type)

边栏推荐
猜你喜欢

已知中序遍历数组和先序遍历数组,返回后序遗历数组

NFT工具合集

众筹DAO“枯萎”的缩影:曾拍下《沙丘》未出版手稿的Spice DAO解散

如何发现新的潜力项目?工具推荐
![[Solution] Emqx startup under win10 reports Unable to load emulator DLL, node.db_role = EMQX_NODE__DB_ROLE = core](/img/c8/d7183330ee86c2cae9c21fecb2805b.png)
[Solution] Emqx startup under win10 reports Unable to load emulator DLL, node.db_role = EMQX_NODE__DB_ROLE = core

How to solve the error when mysql8 installs make

Using the "stack" fast computing -- reverse polish expression

Ansible中的任务执行控制

Graphical LeetCode - 1161. Maximum Sum of In-Layer Elements (Difficulty: Moderate)

REST会消失吗?事件驱动架构如何搭建?
随机推荐
电机原理动图合集
08-SDRAM:汇总
协作乐高 All In One:DAO工具大全
零基础如何学习单片机,一位入门者的进阶路径,可参考
JSP如何使用page指令让JSP文件支持中文编码呢?
NFT工具合集
QML包管理
基于相关性变量筛选偏最小二乘回归的多维相关时间序列建模方法
信息物理系统状态估计与传感器攻击检测
How to solve the error when mysql8 installs make
How to reinstall Win11?One-click method to reinstall Win11
Unknown CMake command “add_action_files“
IP Core: FIFO
els 方块边界变形处理
SphereEx Miao Liyao: Database Mesh R&D Practice under Cloud Native Architecture
Cash Ⅱ LeetCode_518_ change
【解决】win10下emqx启动报错Unable to load emulator DLL、node.db_role = EMQX_NODE__DB_ROLE = core
How does JSP use request to get the real IP of the current visitor?
Ansible中的任务执行控制
[头条]笔试题——最小栈