find-pkg-dir
Find the root directory of a Node.js project from a given path
const findPkgDir = ; // When the /Users/shinnn/foo directory contains a package.json file: ; //=> '/Users/shinnn/foo'; //=> '/Users/shinnn/foo'; //=> '/Users/shinnn/foo'
- It uses
InternalModuleStat
throughrequire.resolve()
as it's faster thanfs.statSync()
. - It checks if a path is file or directory, to avoid mistaking a
package.json
directory as apackage.json
file. - It automatically resolves symbolic links.
Installation
npm install find-pkg-dir
API
const findPkgDir = ;
findPkgDir(path)
path: string
(a path to start searching from)
Return: string
(absolute path) or null
It finds the first directory containing a package.json
file, recursively looking up, starting with the given path.
When it cannot find any package.json
files finally, returns null
.
; //=> null
Benchmark
find-pkg-dir (this project):
Find from the current directory 6.514971999917179 ms/op avg.
Find from the deep directory 301.970978999976069 ms/op avg.
Resolve symlinks 4.765490400046110 ms/op avg.
Find from the `package.json` directory 33.653173299971968 ms/op avg.
find-pkg + path.dirname():
Find from the current directory 7.597467000037431 ms/op avg.
Find from the deep directory 421.827792199980479 ms/op avg.
Resolve symlinks N/A (operation failed)
Find from the `package.json` directory N/A (operation failed)
find-root:
Find from the current directory 8.991230100020767 ms/op avg.
Find from the deep directory 479.851285400055360 ms/op avg.
Resolve symlinks N/A (operation failed)
Find from the `package.json` directory N/A (operation failed)
pkg-dir:
Find from the current directory 9.322520200069993 ms/op avg.
Find from the deep directory 505.923578500002634 ms/op avg.
Resolve symlinks N/A (operation failed)
Find from the `package.json` directory N/A (operation failed)
License
ISC License © 2018 - 2019 Shinnosuke Watanabe