Last active
August 31, 2018 16:38
-
-
Save BananaAcid/65799074691f206c20a28f2253c8c5b2 to your computer and use it in GitHub Desktop.
url exists in node - awaitable async ES6 solution, doing a HEAD request
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//** https://stackoverflow.com/questions/26007187/node-js-check-if-a-remote-url-exists/51757188#51757188 | |
// options for the http request | |
let options = { | |
host: 'google.de', | |
//port: 80, optional | |
//path: '/' optional | |
} | |
const http = require('http'); | |
(async () => { | |
// creating a promise (all promises a can be awaited) | |
let isOk = await new Promise(resolve => { | |
// trigger the request ('HEAD' or 'GET' - you should check if you get the expected result for a HEAD request first (curl)) | |
// then trigger the callback | |
http.request({method:'HEAD', host:options.host, port:options.port, path: options.path}, result => | |
resolve(result.statusCode >= 200 && result.statusCode < 400) | |
).on('error', resolve).end(); | |
}); | |
// check if the result was NOT ok | |
if (!isOk) | |
console.error('could not get: ' + options.host); | |
else | |
console.info('url exists: ' + options.host); | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment