Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
[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
You can’t perform that action at this time.