Created
February 5, 2023 19:28
-
-
Save oscarmarina/a74b0dd70ae472c5a00518475ff1b0a0 to your computer and use it in GitHub Desktop.
Traverse the directory tree in Node.js, starting from the current working directory, searching for a "package.json" file with a specific attribute while excluding the node_modules folder and files starting with a dot (.)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import fs from 'fs'; | |
| import path from 'path'; | |
| const traverseTree = (dir, attribute, cacheTravese = '') => { | |
| const files = fs.readdirSync(dir); | |
| for (const file of files) { | |
| if ( | |
| file === 'node_modules' || | |
| file.startsWith('.') || | |
| file === cacheTravese | |
| ) { | |
| // eslint-disable-next-line no-continue | |
| continue; | |
| } | |
| const filePath = path.join(dir, file); | |
| const stats = fs.statSync(filePath); | |
| if (stats.isDirectory()) { | |
| const found = traverseTree(filePath, attribute); | |
| if (found) { | |
| return found; | |
| } | |
| } else if (file === 'package.json') { | |
| const contents = fs.readFileSync(filePath, 'utf-8'); | |
| const json = JSON.parse(contents); | |
| if (json[attribute]) { | |
| return filePath; | |
| } | |
| } | |
| } | |
| return null; | |
| }; | |
| const findPackageJson = (dir, attribute, cacheTravese = '') => { | |
| const foundPath = traverseTree(dir, attribute, cacheTravese); | |
| if (foundPath) { | |
| return foundPath; | |
| } | |
| if (dir !== '/') { | |
| const parentDir = path.resolve(dir, '..'); | |
| const cachePrevDir = path.basename(dir); | |
| return findPackageJson(parentDir, attribute, cachePrevDir); | |
| } | |
| return null; | |
| }; | |
| const cwd = process.cwd(); | |
| const attributeKey = 'workspaces'; | |
| const foundPath = findPackageJson(cwd, attributeKey); | |
| if (foundPath) { | |
| console.info( | |
| `Found package.json with attribute ${attributeKey} at: ${foundPath} | |
| relative path from cwd: ${cwd} ==> ${path.dirname( | |
| path.relative(cwd, foundPath) | |
| )}` | |
| ); | |
| } else { | |
| console.info( | |
| `No package.json with attribute ${attributeKey} found in workspace tree` | |
| ); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment