'What is the common way to strip out the parent directory from the path in nodejs?

Say the path is /foo/bar/baz.json and I want /bar/baz.json. What's the general way of doing that using nodejs path?



Solution 1:[1]

What about:

var path = require('path');

var myPath = "/foo/bar/baz.json";

var pathItems = myPath.split(path.sep);

pathItems = pathItems.splice(2);
var result = path.sep + pathItems.join(path.sep);

console.log(result);

// "/bar/baz.json"

You might use path.isAbsolute() to decide what to do with the first "/".

Solution 2:[2]

There is a built in function for that in Node.js:

require('path').relative('/foo', '/foo/bar/baz.json');
// 'bar/baz.json'

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Juan Stiza
Solution 2 fishbone