Skip to content

Commit

Permalink
dns: Refactor forEach to map
Browse files Browse the repository at this point in the history
Refactor a forEach to a `map` in the `setServers` function of the
dns module - simplifying the code. In addition, use more descriptive
variable names and `const` over `var` where possible.

PR-URL: #5803
Reviewed-By: Colin Ihrig <cjihrig@gmail.com>
Reviewed-By: Сковорода Никита Андреевич <chalkerx@gmail.com>
  • Loading branch information
benjamingr committed Mar 22, 2016
1 parent 03e07d3 commit 4985c34
Showing 1 changed file with 16 additions and 20 deletions.
36 changes: 16 additions & 20 deletions lib/dns.js
Original file line number Diff line number Diff line change
@@ -285,41 +285,37 @@ exports.getServers = function() {
exports.setServers = function(servers) {
// cache the original servers because in the event of an error setting the
// servers cares won't have any servers available for resolution
var orig = cares.getServers();
const orig = cares.getServers();

var newSet = [];

servers.forEach(function(serv) {
var ver = isIP(serv);

if (ver)
return newSet.push([ver, serv]);

var match = serv.match(/\[(.*)\](:\d+)?/);
const newSet = servers.map((serv) => {
var ipVersion = isIP(serv);
if (ipVersion !== 0)
return [ipVersion, serv];

const match = serv.match(/\[(.*)\](:\d+)?/);
// we have an IPv6 in brackets
if (match) {
ver = isIP(match[1]);
if (ver)
return newSet.push([ver, match[1]]);
ipVersion = isIP(match[1]);
if (ipVersion !== 0)
return [ipVersion, match[1]];
}

var s = serv.split(/:\d+$/)[0];
ver = isIP(s);
const s = serv.split(/:\d+$/)[0];
ipVersion = isIP(s);

if (ver)
return newSet.push([ver, s]);
if (ipVersion !== 0)
return [ipVersion, s];

throw new Error(`IP address is not properly formatted: ${serv}`);
});

var r = cares.setServers(newSet);
const errorNumber = cares.setServers(newSet);

if (r) {
if (errorNumber !== 0) {
// reset the servers to the old servers, because ares probably unset them
cares.setServers(orig.join(','));

var err = cares.strerror(r);
var err = cares.strerror(errorNumber);
throw new Error(`c-ares failed to set servers: "${err}" [${servers}]`);
}
};

0 comments on commit 4985c34

Please sign in to comment.