Parsing URL Querystrings with Node.JS
I've previously written about Parsing Key-Value URL Fragments with Node.JS, but I realised earlier that I don't have an alternative for querystrings.
Following the same pattern, we can use the url
module to actually parse our URL out, and then the querystring
module to extract the key-value parameters for the querystring, instead of hand-rolling our own:
const url = require('url');
const querystring = require('querystring');
const theUrl = 'https://example.com/auth/callback?code=foo&state=blah';
var querystringParams = querystring.parse(url.parse(theUrl).query);
console.log(querystringParams);
// Object: null prototype] { code: 'foo', state: 'blah' }
console.log(JSON.stringify(querystringParams, null, 4));
/*
{
"code": "foo",
"state": "blah"
}
*/
And for a handy one-liner, which will let you optionally specify the parameter to display:
# note the required use of `--` at the end!
$ echo 'https://example.com/auth/callback?code=foo&state=blah' | node -r fs -r process -r querystring -r url -e 'q = querystring.parse(url.parse(fs.readFileSync("/dev/stdin", "utf-8")).query);console.log((process.argv.slice(0)[1]) ? (q[process.argv.slice(0)[1]] || "") : JSON.stringify(q, null, 4));' -- code