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

397
June 15, 2017, at 10:49 AM

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 ;)).

Answer 1

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);
});
Rent Charter Buses Company
READ ALSO
Mongoose Model Object behaves strangely

Mongoose Model Object behaves strangely

I am using mongoose to get person data from databaseThis is the code i use:

275
when does 'end' or 'close' get called on tls.connect

when does 'end' or 'close' get called on tls.connect

For examples like this: https://bravenewmethodcom/2011/02/21/node-js-tls-client-example/

258
node app instance name when running via pm2 cluster

node app instance name when running via pm2 cluster

I have backend node app, that is run by pm2 in cluster modeI'm running fixed 2 instances

622
Including files not present in repository

Including files not present in repository

This is kind of a general question, I've never had to deploy my own code and I'm not sure how to go about doing this properly

273