-
Notifications
You must be signed in to change notification settings - Fork 151
/
is-text.ts
35 lines (28 loc) · 942 Bytes
/
is-text.ts
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
const _isText = require("istextorbinary").isText;
const jsRegex = /(t|j)sx?$/i;
const FILE_LOADER_REGEX = /\.(ico|jpg|png|gif|eot|otf|webp|ttf|woff|woff2|mp4|webm)(\?.*)?$/i;
export const MAX_FILE_SIZE = 512 * 1024;
export const isText = (filename: string, buffer: Buffer) => {
if (jsRegex.test(filename)) {
return true;
}
return new Promise((resolve, reject) => {
_isText(filename, buffer, (err: Error, result: boolean) => {
if (err) {
return reject(err);
}
// We don't support null bytes in the database with postgres,
// so we need to mark it as binary if there are null bytes
const hasNullByte = buffer.toString().includes("\0");
resolve(
result &&
!FILE_LOADER_REGEX.test(filename) &&
!isTooBig(buffer) &&
!hasNullByte
);
});
});
};
export const isTooBig = (buffer: Buffer) => {
return buffer.length > MAX_FILE_SIZE;
};