Skip to content

Instantly share code, notes, and snippets.

@bag-man
Last active May 20, 2016 11:22
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 bag-man/aa5ff6d94c96bf5117a219b72ce6e508 to your computer and use it in GitHub Desktop.
Save bag-man/aa5ff6d94c96bf5117a219b72ce6e508 to your computer and use it in GitHub Desktop.
[NodeJS] Evaluate a URL to get it's domain and port, HTTP(s) only
'use strict'
const url = require('url')
function getUrl (dataUrl) {
if (dataUrl.split('://').length === 1 || dataUrl.startsWith('://')) {
dataUrl = `http://${dataUrl.replace('://', '')}`
}
return dataUrl
}
let findUrlKey = (rawUrl) => {
rawUrl = getUrl(rawUrl)
let inputUrl = url.parse(rawUrl)
, domain = inputUrl.hostname || inputUrl.pathname.split('/')[0]
, protocol = inputUrl.protocol || 'http'
, port = inputUrl.port || (protocol.indexOf('https') > -1 ? '443' : '80')
return domain + ':' + port
}
module.exports = findUrlKey
const assert = require('assert')
, findUrlKey = require('../lib/find-url-key')
, fixtures =
[ { url: 'http://google.com', result: 'google.com:80' }
, { url: 'https://google.com', result: 'google.com:443' }
, { url: 'https://google.com:3000', result: 'google.com:3000' }
, { url: 'http://google.com:3000', result: 'google.com:3000' }
, { url: 'http://google.com:3000/path', result: 'google.com:3000' }
, { url: 'http://google.com:3000', result: 'google.com:3000' }
, { url: 'google.com', result: 'google.com:80' }
, { url: 'google.com/path', result: 'google.com:80' }
, { url: 'google.com:3000/path', result: 'google.com:3000' }
, { url: 'google.com:3000', result: 'google.com:3000' }
, { url: '://google.com:3000', result: 'google.com:3000' }
, { url: '://google.com', result: 'google.com:80' }
, { url: 'ftp://google.com:3000', result: 'google.com:3000' }
, { url: 'ftp://google.com', result: 'google.com:80' }
, { url: 'ftp://google.com:3000/a/bunch?=of werid+stuff#to-see\/ifi:tb.reaks', result: 'google.com:3000' }
, { url: 'google.com/a/bunch?=of werid+stuff#to-see\/ifi:tb.reaks', result: 'google.com:80' }
]
describe('Test URL parsing logic', () => {
fixtures.forEach((fixture) => {
it('should return: ' + JSON.stringify(fixture.result), (done) => {
assert.deepEqual(findUrlKey(fixture.url), fixture.result, 'wrong domain or port found')
done()
})
})
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment