当前位置:网站首页>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)

边栏推荐
猜你喜欢

如何发现新的潜力项目?工具推荐

Detailed explanation of Zadig's self-testing and tuning environment technical solution for developers

Redis-消息发布订阅

Don't know about SynchronousQueue?So ArrayBlockingQueue and LinkedBlockingQueue don't and don't know?

【三子棋】C语言实现简易三子棋

GetHashCode与Equals

Arduino 基础语法

当奈飞的NFT忘记了Web2的业务安全

中缀转后缀、前缀表达式快速解决办法

Play NFT summer: this collection of tools is worth collecting
随机推荐
How does JSP use the page command to make the JSP file support Chinese encoding?
When Netflix's NFTs Forget Web2 Business Security
SphereEx苗立尧:云原生架构下的Database Mesh研发实践
els 方块变形判断。
不了解SynchronousQueue?那ArrayBlockingQueue和LinkedBlockingQueue不会也不知道吧?
08-SDRAM:汇总
LeetCode_518_零钱兑换Ⅱ
JSP out.print()和out.write()方法的不同之处
电机原理动图合集
JSP如何使用request获取当前访问者的真实IP呢?
Redis-消息发布订阅
async/await 原理及执行顺序分析
JSP内置对象out对象的功能简介说明
Using the "stack" fast computing -- reverse polish expression
146. LRU 缓存
els 方块边界变形处理
security跨域配置
What is the function of the JSP out.println() method?
零基础如何学习单片机,一位入门者的进阶路径,可参考
一文概览最实用的 DeFi 工具