jsdario jsdario - 4 months ago 28x
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?


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