-
Notifications
You must be signed in to change notification settings - Fork 326
/
Copy pathmime-sniff.js
45 lines (39 loc) · 1.21 KB
/
mime-sniff.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
'use strict'
/* eslint-env browser, webextensions */
const docSniff = require('doc-sniff')
const fileType = require('file-type')
const mime = require('mime-types')
/*
* A quick, best effort mime sniffing fn, via:
* @see https://github.com/sindresorhus/file-type
* @see https://github.com/bitinn/doc-sniff
*
* buffer => 'mime/type'
*
* TODO: https://mimesniff.spec.whatwg.org/
*/
exports.mimeSniff = function (buff, path) {
// deals with buffers, and uses magic number detection
const fileTypeRes = fileType(buff)
if (fileTypeRes) {
const pathSniffRes = mime.lookup(path)
if (fileTypeRes.mime === 'application/xml' && pathSniffRes === 'image/svg+xml') {
// detected SVGs
return pathSniffRes
}
return fileTypeRes.mime
}
const str = buff.toString('utf8')
// minimal whatwg style doc sniff.
const docSniffRes = docSniff(false, str)
if (docSniffRes === 'text/plain' && mime.lookup(path) === 'text/markdown') {
// force plain text, otherwise browser triggers download of .md files
return 'text/plain'
}
if (!docSniffRes || docSniffRes === 'text/plain') {
// fallback to guessing by file extension
return mime.lookup(path)
} else {
return docSniffRes
}
}