This approach works well in Python, but JavaScript makes it a bit clunky.  Maybe setting root to null initially and doing 

  if (root !== null && root !== pathInfo.dirname) {

would be better.