Parsing URL Querystrings with Node.JS

Featured image for sharing metadata for article

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 = '';
var querystringParams = querystring.parse(url.parse(theUrl).query);
// 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 '' | 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

Written by Jamie Tanna's profile image Jamie Tanna on , and last updated on .

Content for this article is shared under the terms of the Creative Commons Attribution Non Commercial Share Alike 4.0 International, and code is shared under the Apache License 2.0.

#nodejs #blogumentation #nablopomo.

This post was filed under articles.

This post is part of the series nablopomo-2019.

Interactions with this post

Interactions with this post

Below you can find the interactions that this page has had using WebMention.

Have you written a response to this post? Let me know the URL:

Do you not have a website set up with WebMention capabilities? You can use Comment Parade.