June
June

Reputation: 823

Way to get file name and parent directory name

I am building an application a react/redux based application and looking for a best way to get parent directory and filename form url. URL do not have domain name so it only have the path after the domain name for eg

/directory1/index.html?v=1.1
// need to get /directory1/index.html?v=1.1

directory1/directory2/dircetory3/index.html?v=1.1
// need to get directory2/index.html?v=1.1

/index.html?v=1.1
// need to get only index.html?v=1.1 as no parent directory is available

/immediateParentDirectory/filename.html

I tried creating a regex but want able to just wanted to confirm if there is already existing node module that does that before I reinvent the wheel

Upvotes: 0

Views: 974

Answers (2)

Soviut
Soviut

Reputation: 91615

You can .split('/') the URL on the forward slash character /. Then .slice(-2) to get the last 2 items from the split items. Then .join('/') those two items back together with a slash.

function parentPath(url) {
  return url.split('/').slice(-2).join('/')
}

console.log(parentPath('/directory1/index.html?v=1.1'))    
console.log(parentPath('directory1/directory2/dircetory3/index.html?v=1.1'))    
console.log(parentPath('/index.html?v=1.1'))
console.log(parentPath('index.html?v=1.1'))

Upvotes: 2

Felix Kling
Felix Kling

Reputation: 816970

You can use path.dirname and path.basename:

function doSomething(p) {
  const dir = path.dirname(p);
  // takes care of `foo` and `/foo`
  if (dir === '.' || dir === '/') {
    return p;
  }

  return path.basename(dir) + '/' + path.basename(p);
}

This assumes that you are not having paths with relative sections, such as foo/bar/..baz/ or ./foo.

It's unclear to me whether you want a leading / or not, but that's also easy to add or remove by checking result[0] === '/'.

Upvotes: 0

Related Questions