jfw10973
jfw10973

Reputation: 31

Node.js path.join reverse operation

Example in Node.js API

path.join('/foo', 'bar', 'baz/asdf', 'quux', '..');
// Returns: '/foo/bar/baz/asdf'

But how to get "/foo/bar" from '/foo/bar/baz/asdf' and ''baz/asdf'' ?

path.magic('/foo/bar/baz/asdf', 'baz/asdf')
//Returns: '/foo/bar/'

Upvotes: 1

Views: 1079

Answers (1)

ZeroCho
ZeroCho

Reputation: 1360

I think there's no native method for doing that.

I think the best way to do that is to use path.join('/foo/bar/baz/asdf', '..', '..');

you can make your own function like below

const magic = function(originalPath, removePath) {
  let arr = removePath.split('/').filter((p) => p !== '').map(() => '..');
  return path.join(originalPath, ...arr);
}

You might need to use path.sep instead of '/' to support various OS.

Upvotes: 2

Related Questions