jsdario jsdario - 1 year ago 158
Node.js Question

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
, there should be 2 events emmited:

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?

Answer Source

Use indexOf is enough.

function isParentOf(parent, dir) {
  return dir.indexOf(parent) === 0;

isParentOf('test/replyer/request/@issuer', 'test') // true
isParentOf('test/replyer/request/@issuer', 'replyer/request') // false
isParentOf('test/replyer/request/@issuer', 'test/replyer/request') // true
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download