Skip to content

Instantly share code, notes, and snippets.

@andreasvirkus
Created April 29, 2018 08:24
Show Gist options
  • Save andreasvirkus/93750e1287f723f2f5bb8d89122fabab to your computer and use it in GitHub Desktop.
Save andreasvirkus/93750e1287f723f2f5bb8d89122fabab to your computer and use it in GitHub Desktop.
lightweight Node Promise-based request module
const http = require('http')
const https = require('https')
const url = require('url')
module.exports = {
urlCheck,
request
}
function urlCheck(url) {
return request(url)
.then(headers => {
switch(ParseInt(headers.statusCode / 100, 10)) {
case 3:
return request(headers.location)
case 4:
Promise.reject(headers)
default:
return Promise.resolve(headers)
}
})
}
function request(link) {
const parsedURL = url.parse(link)
const options = {
protocol: parsedURL.protocol,
hostname: parsedURL.hostname,
method: 'HEAD',
path: parsedURL.path
}
let protocolHandler = parsedURL.protocol === 'https:' ? https : http
return new Promise((resolve, reject) => {
const req = protocolHandler.request(options, (res) => {
resolve(res.headers)
})
req.on('error', (e) => reject(e))
req.end()
})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment