Say you want to check if the directory name of a project matches its
module name in package.json:
const path = require('path')const findRoot = require('find-root')// from a starting directory, recursively search for the nearest// directory containing package.jsonconst root = findRoot('/Users/jsdnxx/Code/find-root/tests')// => '/Users/jsdnxx/Code/find-root'const dirname = path.basename(root)console.log('is it the same?')console.log(dirname === require(path.join(root, 'package.json')).name)
You can also pass in a custom check function (by default, it checks for the
existence of package.json in a directory). In this example, we traverse up
to find the root of a git repo: