Last active
March 21, 2023 22:07
-
-
Save david-luna/bddd718770405fc5c8bb4d61d297e122 to your computer and use it in GitHub Desktop.
url-parsing-comparison
This file contains 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
# Script to compare URL parsing between: url.parse, whatwg URL & request-target |
This file contains 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 { URL, parse } = require('url') | |
const requestTarget = require('request-target') | |
const method = 'GET' | |
const headers = { host: 'localhost' } | |
const urls = [ | |
'/', | |
'/some/path', | |
'//some/path', | |
'/user@pass', | |
'//user@pass', | |
'/some/path?key=value', | |
'@@', | |
'///', | |
] | |
const results = urls.map((url) => ({ | |
'request-target': requestTarget({ headers, method, url }), | |
'new-url': getUrl(url), | |
'url-parse': parse(url), | |
})); | |
const baseCounter = { 'request-target': 0, 'new-url': 0, 'url-parse': 0 }; | |
const resultKeys = Object.keys(baseCounter); | |
const counters = results.reduce((acc, current) => { | |
resultKeys.forEach((k) => acc[k] += current[k] ? 1 : 0) | |
return acc; | |
}, baseCounter); | |
const props = ['protocol', 'host', 'pathname']; | |
results.forEach((result, index) => { | |
let table = '' | |
// header | |
table += '| ' + ['method', ...props].join(' | ') + ' |\n' | |
table += '| ' + ['method', ...props].map(x => '-').join(' | ') + ' |\n' | |
// rows | |
Object.keys(result).forEach((key) => { | |
const res = result[key]; | |
const values = props.map((p) => res ? res[p] : 'N/A') | |
table += '| ' + [key, ...values].join(' | ') + ' |\n' | |
}); | |
console.log(`Parse results for **${urls[index]}**`) | |
console.log(table) | |
}) | |
console.log(`Urls parsed by method`) | |
console.log(`| ${resultKeys.join(' | ')} | total |`) | |
console.log(`| ${resultKeys.map(k => '-').join(' | ')} | - |`) | |
console.log(`| ${resultKeys.map(k => counters[k]).join(' | ')} | ${urls.length} |`) | |
function getUrl(url) { | |
try { | |
return new URL(`http://${url}`) | |
} catch (e) { | |
return null | |
} | |
} |
This file contains 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
{ | |
"name": "original-url-pull-11", | |
"version": "0.0.0", | |
"private": true, | |
"dependencies": { | |
"request-target": "1.0.2" | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment