2017-06-14 61 views
0

我想對域名做一個查詢(我會遍歷一大堆)看看它們是否存在。我希望任何不存在的域名都返回一個布爾型的假和任何返回域名本身的域名(這樣我就可以將它保存到一個文件中)。目前,我有:檢查域名是否與節點存在,返回布爾值假如果沒有,返回域名如果它確實

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

這很基本的,但我一直在與大半夜的Python和Java代碼庫擒拿我真正想要的是一個if語句來檢查URL的有效性而不必煩惱頭部,如果我改變了上面的代碼,我就不得不這樣做。

基本上我只是想:

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

道歉的僞代碼。指針歡迎(是的,我知道JavaScript沒有指針;))。

+0

也許,而不是試圖找出他們是否_respond_,你應該使用['dns'](https://nodejs.org/ api/dns.html)找出他們是否存在_exist_。 –

+0

@PatrickRoberts我很想知道如何做到這一點。雖然tbh我寧願知道他們是否迴應,知道他們存在至少會有用。 –

+0

@PatrickRoberts你能否提供一個答案告訴我如何檢查它們是否存在? –

回答

0

使用dns喜歡我的建議,你可以做到以下幾點:

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); 
}); 
相關問題