Skip to content
Advertisement

Determine if a path is subdirectory of another in Node.js

I am working on a MQTT handler for which I want to emit an event for each parent directory where there is a event listener. For example:

If there are the following MQTT paths available, where there are subscriptors –there are event listeners for these paths–

  • test
  • replyer/request
  • test/replyer/request

And someone publishes on topic test/replyer/request/@issuer, there should be 2 events emmited: test, test/replyer/request.

Given than any path is possible and there is no list of available valid events, we must check only if a path is a parent of another. Can we do this with regex? If so, how would it look like? Is there a simpler/more efficient solution?

Advertisement

Answer

2021 Answer

Use @Ilya’s solution.

2017 Answer

In ES6.

const isChildOf = (child, parent) => {
  if (child === parent) return false
  let parentTokens = parent.split('/').filter(i => i.length)
  let childTokens = child.split('/').filter(i => i.length)
  return parentTokens.every((t, i) => childTokens[i] === t)
}

If you’re working in node.js and you want to make it cross-platform, include the path module and replace split('/') with split(path.sep).


How it works:

So, you want to find out if a directory (like home/etc/subdirectory) is a subdirectory of another directory (like home/etc).

It takes both the hypothesised child and parent paths and convert them into arrays using split:

['home', 'etc', 'subdirectory'], ['home', 'etc']

It then iterates through all of the tokens in the parent array and checks them one-by-one against their relative position in the child array using ES6’s .every().

If everything in parent matches up to everything in child, knowing that we’ve ruled out they are exactly the same directory (using child !== parent), we will have our answer.

Advertisement