Skip to content

Instantly share code, notes, and snippets.

@BananaAcid
Last active August 31, 2018 16:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BananaAcid/65799074691f206c20a28f2253c8c5b2 to your computer and use it in GitHub Desktop.
Save BananaAcid/65799074691f206c20a28f2253c8c5b2 to your computer and use it in GitHub Desktop.
url exists in node - awaitable async ES6 solution, doing a HEAD request
//** 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