-
Notifications
You must be signed in to change notification settings - Fork 8
/
nslookup.js
115 lines (95 loc) · 2.25 KB
/
nslookup.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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
var dns = require('native-dns');
function makeError(name, msg) {
var err = new Error(msg);
err.name = 'NSLookup' + name + 'Error';
return err;
}
function Lookup() {
this.domainName = null;
this.domainType = 'a';
this.serverAddr = '8.8.8.8';
this.serverPort = 53;
this.serverType = 'udp';
this._timeout = 3 * 1000;
}
Lookup.prototype.type = function (type) {
type = type.toLowerCase();
if (type === 'cname' || type === 'soa' || type === 'srv') {
throw makeError('NotSupport', 'do not support type: ' + type);
}
this.domainType = type;
return this;
};
Lookup.prototype.server = function (server) {
if (typeof server === 'string') {
this.serverAddr = server;
}
if (typeof server === 'object') {
this.serverAddr = server.address;
this.serverPort = server.port;
this.serverType = server.type;
}
return this;
};
// ms
Lookup.prototype.timeout = function (timeout) {
this._timeout = timeout;
return this;
};
function extracterBuilder(type) {
var prop = null;
if ('a' === type) {
prop = 'address';
} else if ('mx' === type) {
prop = 'exchange';
} else if ('ns' === type || 'txt' === type) {
prop = 'data';
} else {
prop = 'address';
}
return function (addr) {
return addr[prop];
};
}
Lookup.prototype.end = function (callback) {
var self = this;
var question = dns.Question({
name: this.domainName,
type: this.domainType,
});
var server = {
address: this.serverAddr,
port: this.serverPort,
type: this.serverType,
};
var timeout = this._timeout;
var req = dns.Request({
question: question,
server: server,
timeout: timeout,
});
req.on('timeout', function () {
callback(makeError('Timeout', 'dns request exceed ' + timeout + 'ms'));
});
req.on('message', function (err, answer) {
if (err) {
return callback(err);
}
var extracter = extracterBuilder(self.domainType);
var addrs = answer.answer.map(function (a) {
return extracter(a);
});
callback(null, addrs);
});
req.on('end', function () {
});
req.send();
};
exports = module.exports = function (name, callback) {
var lookup = new Lookup();
lookup.domainName = name;
if (callback) {
lookup.end(callback);
}
return lookup;
};