Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting an absolute path to a relative path

Working in Node I need to convert my request path into a relative path so I can drop it into some templates that have a different folder structure.

Basically if I start with the path "/foo/bar" I need my relative path to be ".." If it's "/foo/bar/baz" I need it to be "../.."

I wrote a pair of functions to do this:

function splitPath(path) {
    return path.split('/').map(dots).slice(2).join('/');
}

function dots() {
    return '..';
}

Not sure if this is the best approach or if it's possible to do it with a regular expression in String.replace somehow?

edit

I should point out this is so I can render everything as static HTML, zip up the whole project, and send it to someone who doesn't have access to a web server. See my first comment.

like image 404
robdodson Avatar asked Sep 15 '12 15:09

robdodson


1 Answers

If I understand you question correct you can use path.relative(from, to)

Documentation

Example:

var path = require('path');
console.log(path.relative('/foo/bar/baz', '/foo'));
like image 144
Mattias Avatar answered Oct 12 '22 12:10

Mattias