forked from 7c/whoisserver-world
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (76 loc) · 2.67 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
const path = require('path')
const fs = require('fs')
const tlds_folder = path.join(__dirname,'tlds')
const json_path = path.join(__dirname,'whoisservers.json')
const TLDS = tlds()
/**
* returns object of TLD or false if tld is not known
* @param {string} tld
* @returns {} tld object|false
*/
function tldDetails(tld) {
if (typeof tld==='string') {
tld=tld.toLowerCase().trim().replace(/[^a-z0-9-]/,'')
var fn = path.join(tlds_folder,tld+'.json')
if (fs.existsSync(fn)) {
try {
var data = fs.readFileSync(fn,'ascii')
return JSON.parse(data)
}
catch(err) { }
}
}
return false
}
/**
* returns all TLDs as iteration JSON object or false in case of error
*/
function tlds() {
// reading as file will make sure that we read new file upon package renewal
try {
return JSON.parse(fs.readFileSync(json_path,'utf8'))
}catch(err) {}
return false
}
function parseDomain(hostname) { // test exists // this requires whoisserver-world
if (typeof hostname === 'string') {
let ret = {
hostname: hostname.toLowerCase(),
tldData: false,
domain: '',
tld:''
}
let parts = hostname.split('.')
if (parts.length < 2) return null
let last2 = (parts[parts.length - 2] + '.' + parts[parts.length - 1]).toLowerCase()
// do we have last2 ?
let last1 = parts[parts.length - 1].toLowerCase()
if (TLDS.hasOwnProperty(last1)) {
let tldData = TLDS[last1]
ret.tldData = tldData
ret.tld = tldData.tld
if (tldData.hasOwnProperty('sampleDomains')) {
ret.domain = last2
// domains like cm.gov.nc.tr (north-cypern)
if (parts.length > 3) {
let last3 = (parts[parts.length - 3] + '.' + parts[parts.length - 2] + '.' + parts[parts.length - 1]).toLowerCase()
if (tldData.sampleDomains.hasOwnProperty(last3)) {
ret.domain = (parts[parts.length - 4] + '.' + parts[parts.length - 3] + '.' + parts[parts.length - 2] + '.' + parts[parts.length - 1]).toLowerCase()
return ret
}
}
if (parts.length > 2 && tldData.sampleDomains.hasOwnProperty(last2)) {
ret.domain = (parts[parts.length - 3] + '.' + parts[parts.length - 2] + '.' + parts[parts.length - 1]).toLowerCase()
return ret
}
return ret
}
}
}
return null
}
module.exports={
tldDetails,
tlds,
parseDomain
}