-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
88 lines (83 loc) · 2.08 KB
/
index.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
'use strict';
const { fromBuffer, fromFile } = require('file-type');
const { lookup, extension } = require('mime-types');
const {
isString, isObject, isBuffer, isStream, isExists,
streamChunk, BUFFER_LENGTH
} = require('./utils');
/**
* @param {Object} [data]
* @param {String} [data.ext]
* @param {String} [data.mime]
* @param {String} [data.type]
* @returns {{ ext: String, mime: String }|null}
*/
function defaultData(data) {
if (!data) {
return null;
}
if (isString(data)) {
const mime = lookup(data);
if (mime) {
return { ext: extension(mime), mime };
}
const ext = extension(data);
if (ext) {
return { ext, mime: lookup(ext) };
}
} else if (isObject(data)) {
if (data.ext) {
const { ext } = data;
const mime = lookup(ext);
if (mime) {
return { ext, mime };
}
}
if (data.mime || data.type) {
const mime = data.mime || data.type;
const ext = extension(mime);
if (ext) {
return { ext, mime };
}
}
}
return null;
}
/**
* Asynchronously determines MIME type of input
* @param {String|Buffer|Uint8Array|ArrayBuffer|ReadableStream} input
* @param {Object} [defaultValue]
* @param {String} [defaultValue.ext]
* @param {String} [defaultValue.mime]
* @param {String} [defaultValue.type]
* @returns {Promise<{ ext: String, mime: String }|null>}
* @async
*/
async function async(input, defaultValue) {
if (input) {
let file;
if (isString(input)) {
const mime = lookup(input);
if (mime) {
return { ext: extension(mime), mime };
}
if (await isExists(input)) {
file = await fromFile(input);
}
} else if (isBuffer(input)) {
file = await fromBuffer(input);
} else if (isStream(input)) {
const chunk = await streamChunk(input);
if (chunk) {
file = await fromBuffer(chunk);
}
}
if (file !== undefined && file !== null) {
return file;
}
}
return defaultData(defaultValue);
}
module.exports = async;
module.exports.async = async;
module.exports.BUFFER_LENGTH = BUFFER_LENGTH;