-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmagic-number.js
50 lines (38 loc) · 1.03 KB
/
magic-number.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
"use strict";
/**
*
* https://www.garykessler.net/library/file_sigs.html
*
**/
// Dependencies
const fs = require('fs');
exports.detect = function ({ filePath }) {
let mns = []; // Magic Numbers as an ASCII string
let exts = [];
let data = fs.readFileSync(filePath);
let type = 'Unknown';
loadFiletypes(mns, exts);
for (let i = 0; i < mns.length; i++) {
let file_mn = '';
// Convert file's decimal magic numbers to an ASCII string
for (let x = 0; x < mns[i].length; x++) {
file_mn += String.fromCharCode(data[x]);
}
if (file_mn == mns[i]) {
type = exts[i];
break;
}
}
return type;
}
function loadFiletypes(mns, exts) {
const data = fs.readFileSync('file.types', 'utf8');
let lines = data.split('\n');
for (let i = 0; i < lines.length; i++) {
const split = lines[i].split(':');
if (split[0] != '') {
exts.push(split[0]);
mns.push(split[1].trimEnd());
}
}
}