Peter Carter
Peter Carter

Reputation: 2728

Check if domain name exists with node, return boolean false if not, return domain name if it does

I'm trying to do a query on domain names (I'll be looping through a whole bunch) seeing if they exist. I'd like for any domain names that don't exist to return a boolean false and any that do to return the domain name itself (so I can save it to a file). At the moment I have:

var http = require('http'),
    options = {method: 'HEAD', host: 'stackoverflow.com', port: 80, path: '/'};
    req = http.request(options, function(r) {
        console.log(JSON.stringify(r.headers));
    });
req.end();

This very basic, but I've been grappling with Python and Java code libraries for most of the night and all I really want is an if statement that checks the validity of a url without having to mess about with the headers, which I'd have to do if I changed the above code.

Essentially I just want:

if(request === successful) {
  return url;
} else {
  return false;
}

Apologies for the pseudocode. Pointers welcome (yeah, I know there are no pointers for JavaScript ;)).

Upvotes: 4

Views: 4350

Answers (1)

Patrick Roberts
Patrick Roberts

Reputation: 51756

Using dns like I suggested, you can do the following:

const dns = require('dns');

let listOfHostnames = [
  'stackoverflow.com',
  'nodejs.org',
  'developer.mozilla.org',
  'google.com',
  'whatisthisidonteven.net'
];

function hostnameExists(hostname) {
  return new Promise((resolve) => {
    dns.lookup(hostname, (error) => resolve({hostname, exists: !error}));
  });
}

Promise.all(listOfHostnames.map(hostnameExists)).then((listOfStatuses) => {
  // check results here
  console.log(listOfStatuses);
});

With dns.promises you can even implement hostnameExists() without the Promise constructor:

const dnsPromises = require('dns').promises;

async function hostnameExists(hostname) {
  try {
    await dnsPromises.lookup(hostname);
    return { hostname, exists: true };
  } catch (_) {
    return { hostname, exists: false };
  }
}

Upvotes: 10

Related Questions