I’m a big fan of Value Objects - some of the most useful classes I’ve ever written have been lightweight wrappers around strings.
For my first contribution to the node.js ecosystem, I’ve published a simple, immutable URL object to the Node package manager (npm) directory. It provides a light-weight, immutable URL object that encapsulates the functionality of the existing ‘url’ and ‘querystring’ modules in a single object as well as offering various extension methods that make working with URLs easy.
Source and detailed docs available at http://github.com/codeinthehole/nurl -but here’s some sample usage for dynamically building a URL:
var nurl = require("nurl"); var baseUrl = new nurl.Url() .setProtocol("http") .setHostname("api.example.com") .setPathname("search"); var searchUrl = baseUrl.setPathSegment(1, "my search term"); searchUrl.toString(); // => 'http://api.example.com/search/my%20search%20term
All components of a URL are exposed as read-only properties as well as through getter functions.
var u = nurl.parse("http://www.example.com/path/to/somewhere?q=node.js"); u.getSubdomains(); // ['www', 'example', 'com'] u.getPathSegment(0); // 'path' u.getQueryParam("q"); // 'node.js' u.getQueryParam("p", "a default value"); // 'a default value'
All very simple but potentially quite useful thanks to the ubiquity of the humble URL.
All feedback, forks and pull requests gratefully accepted.