Problem
api.js
'use strict';
const http = require('http');
module.exports = url => {
const options = {
host: url,
method: 'HEAD',
path: '/'
};
const req = http.request(options);
req.end();
const promise = new Promise((resolve, reject) => {
let connected = false;
req.on('response', res => {
connected = res.statusCode < 500;
resolve(connected);
});
req.on('error', err => {
reject(err);
});
});
return promise;
};
The most confusing part for me is which status codes should be considered a valid candidate? apart from that any comments regarding code are welcome.
Solution
When the server does not exists it seems node throws an EIO
error.
Now you need to make a decision, you can either reject the promise or resolve with false. From an usage point of view I would say I would prefer to resolve it false unless I need to know why the server is unavailable.
I am assuming that you just want to know if it is available or not, thus it doesn’t make sense to reject the promise ever.
Your module also doesn’t support Urls, in the form of
scheme:[//[user:password@]host[:port]][/]path[?query][#fragment]
In order to support that you must parse the parameter with the existing URL
module.
In order to support both the URL and the URN you can check if the protocol was specified
var http = require('http');
var url = require("url");
var Promise = require('promise');
module.exports = function (uri) {
var address = url.parse(uri);
var parts = uri.split('/');
var options = {
host: address.protocol != null ? address.host : parts[0],
method: 'HEAD',
path: address.protocol != null ? address.pathname : parts.slice(1).join('/')
};
var req = http.request(options);
req.end();
var promise = new Promise(function (resolve, reject) {
var connected = false;
req.on('response', function (res) {
connected = res.statusCode < 500;
resolve(connected);
});
req.on('error', function (err) {
resolve(false);
});
});
return promise;
};
module.exports("http://httpstat.us/200").then(function(isAvailable){
console.log(isAvailable);
});