Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js url.parse result back to string

Tags:

url

node.js

I am trying to do some simple pagination. To that end, I'm trying to parse the current URL, then produce links to the same query, but with incremented and decremented page parameters.

I've tried doing the following, but it produces the same link, without the new page parameter.

var parts = url.parse(req.url, true);
parts.query['page'] = 25;
console.log("Link: ", url.format(parts));

The documentation for the URL module seems to suggest that format is what I need but I'm doing something wrong.

I know I could iterate and build up the string manually, but I was hoping there's an existing method for this.

like image 657
benui Avatar asked Sep 22 '11 15:09

benui


People also ask

What does URL parse do in node JS?

The url. parse() method takes a URL string, parses it, and it will return a URL object with each part of the address as properties. Parameters: This method accepts three parameters as mentioned above and described below: urlString: It holds the URL string which needs to parse.

Which property of the request object provides the request method in node JS?

The req object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.

Which module is used to parse the query string in node JS?

The Query String module provides a way of parsing the URL query string.


3 Answers

If you look at the latest documentation, you can see that url.format behaves in the following way:

  • search will be used in place of query
  • query (object; see querystring) will only be used if search is absent.

And when you modify query, search remains unchanged and it uses it. So to force it to use query, simply remove search from the object:

var url = require("url");
var parts = url.parse("http://test.com?page=25&foo=bar", true);
parts.query.page++;
delete parts.search;
console.log(url.format(parts)); //http://test.com/?page=26&foo=bar

Make sure you're always reading the latest version of the documentation, this will save you a lot of trouble.

like image 188
Alex Turpin Avatar answered Sep 17 '22 17:09

Alex Turpin


Seems to me like it's a bug in node. You might try

// in requires
var url = require('url');
var qs = require('querystring');

// later
var parts = url.parse(req.url, true);
parts.query['page'] = 25;
parts.query = qs.stringify(parts.query);
console.log("Link: ", url.format(parts));
like image 35
Marcel M. Avatar answered Sep 19 '22 17:09

Marcel M.


The other answer is good, but you could also do something like this. The querystring module is used to work with query strings.

var querystring = require('querystring');
var qs = querystring.parse(parts.query);
qs.page = 25;
parts.search = '?' + querystring.stringify(qs);
var newUrl = url.format(parts);
like image 30
ampersand Avatar answered Sep 17 '22 17:09

ampersand