forked from sindresorhus/file-type
-
Notifications
You must be signed in to change notification settings - Fork 0
/
browser.js
51 lines (42 loc) · 1.32 KB
/
browser.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
import {Buffer} from 'node:buffer';
import {ReadableWebToNodeStream} from 'readable-web-to-node-stream';
import {fileTypeFromBuffer, fileTypeFromStream as coreFileTypeFromStream} from './core.js';
/**
Convert Blobs to ArrayBuffer.
@param {Blob} blob - Web API Blob.
@returns {Promise<ArrayBuffer>}
*/
function blobToArrayBuffer(blob) {
if (blob.arrayBuffer) {
return blob.arrayBuffer();
}
// TODO: Remove when stop supporting older environments
return new Promise((resolve, reject) => {
const fileReader = new FileReader();
fileReader.addEventListener('loadend', event => {
resolve(event.target.result);
});
fileReader.addEventListener('error', event => {
reject(new Error(event.message));
});
fileReader.addEventListener('abort', event => {
reject(new Error(event.type));
});
fileReader.readAsArrayBuffer(blob);
});
}
export async function fileTypeFromStream(stream) {
const readableWebToNodeStream = new ReadableWebToNodeStream(stream);
const fileType = await coreFileTypeFromStream(readableWebToNodeStream);
await readableWebToNodeStream.close();
return fileType;
}
export async function fileTypeFromBlob(blob) {
const buffer = await blobToArrayBuffer(blob);
return fileTypeFromBuffer(Buffer.from(buffer));
}
export {
fileTypeFromTokenizer,
fileTypeFromBuffer,
fileTypeStream,
} from './core.js';