Created
April 29, 2018 08:24
-
-
Save andreasvirkus/93750e1287f723f2f5bb8d89122fabab to your computer and use it in GitHub Desktop.
lightweight Node Promise-based request module
This file contains hidden or 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
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