Sign Up for Free

RunKit +

Try any Node.js package right in your browser

This is a playground to test code. It runs a full Node.js environment and already has all of npm’s 400,000 packages pre-installed, including path-rewriter with all npm packages installed. Try it out:

var pathRewriter = require("path-rewriter")

This service is provided by RunKit and is not affiliated with npm, Inc or the package authors.

path-rewriter v1.0.1

A path rewriter for node.js

path-rewriter

NPM version Build Status Dependency Status Coverage percentage

A path rewriter for node.js

Install

$ npm install --save path-rewriter

Examples

Rewrite using a regular expression, rewriting /i123 to /items/123.

var Rewriter = require('path-rewriter'); 
var rewriter = new Rewriter();
rewriter.rule(/^\/i(\w+)/, '/items/$1');
console.log(rewriter.rewrite('/i123'));  // '/items/123'

Rewrite using rule parameters, references may be named or numeric. For example rewrite /foo..bar to /commits/foo/to/bar:

var Rewriter = require('path-rewriter');
var rewriter = new Rewriter();
rewriter.rule('/:src..:dst', '/commits/$1/to/$2');
console.log(rewriter.rewrite('/foo..bar'));  // '/commits/foo/to/bar'

var rewriter = new Rewriter();
rewriter.rule('/:src..:dst', '/commits/:src/to/:dst');
console.log(rewriter.rewrite('/foo..bar'));  // '/commits/foo/to/bar'

You may also use the wildcard * to soak up several segments, for example /js/vendor/jquery.js would become /public/assets/js/vendor/jquery.js:

var Rewriter = require('path-rewriter');
var rewriter = new Rewriter();
rewriter.rule('/js/*', '/public/assets/js/$1');
console.log(rewriter.rewrite('/js/vendor/jquery.js'));  // '/public/assets/js/vendor/jquery.js'

In the above examples, the original query string (if any) is left untouched. The regular expression is applied to the full url, so the query string can be modified as well:

var Rewriter = require('path-rewriter');
var rewriter = new Rewriter();
rewriter.rule('/file\\?param=:param', '/file/:param');
console.log(rewriter.rewrite('/file?param=foo'));  // '/file/foo'

The query string delimiter (?) must be escaped for the regular expression to work.

License

MIT © Tao Yuan

RunKit is a free, in-browser JavaScript dev environment for prototyping Node.js code, with every npm package installed. Sign up to share your code.
Sign Up for Free