递归查找最近的package.json节点. js

jhkqcmku  于 2023-02-06  发布在  其他
关注(0)|答案(2)|浏览(116)

我刚接触到节点js,我想递归地找到最近的package.json,实际上,继续查找package.json,直到不会碰到它。
我的文件夹树

root/
  -contarats/
   -proto/
    some.proto
  -package.json 

"script": {
"contracts": "generate-some-contracts contracts/proto contracts",
}

const input = process.argv[2]
const settings = require(path.resolve(input, 'package.json'))
pnwntuvh

pnwntuvh1#

你在寻找一种遍历目录的方法吗?如果是的话,这里有一个同步函数可以做到这一点

function search_sync(dir) {
var results = []
var list = fs.readdirSync(dir)
list.forEach(function(file) {
    file = path.resolve(dir, file)
    filename = file.split('\\');
    filename = filename[filename.length-1]
    var stat = fs.statSync(file)
    if (stat && stat.isDirectory()) results = results.concat(search_sync(file))
    else if(filename == 'package.json')results.push(file)
})
return results

}
这将返回名为package.json的所有文件及其完整文件路径的数组。

search_sync('./')

[C:\Users\User\MyNodeProject\package.json,
C:\Users\User\MyNodeProject\npm\someDependency\package.json,
C:\Users\User\MyNodeProject\npm\someOtherDependency\package.json]

就我个人而言,我会用"\“字符将每一行断开,然后查看哪一行更接近我的根文件夹

gkl3eglg

gkl3eglg2#

查看目录树,package.json文件不在contracts/proto中,而是在contracts中(我假设contaracts是一个输入错误)。更改命令行上的第一个参数应该会有所帮助:

generate-some-contracts contracts contracts

尽管如此,你还是会问到递归搜索最近的package.json,NPM在查找包根时会这样做,它从当前目录开始,然后沿着祖先目录,直到找到一个package.json,一个阅读和解析package.json的函数,类似于require,可能如下所示:

const { readFile } = require('fs/promises')
const { join, resolve } = require('path')

async function loadPackageJson(cwd) {
  const startDir = cwd || process.env.INIT_CWD || process.cwd()
  let dir = startDir, prevDir
  do {
    try {
      const path = join(dir, 'package.json')
      const content = await readFile(path, 'utf8')
      return JSON.parse(content)
    } catch (err) {
      if (err.code !== 'ENOENT') throw err
    }
    prevDir = dir
    dir = resolve(dir, '..')
  } while (prevDir !== dir)
  throw new Error(`package.json not found in ${startDir} and its ancestors`)
}

相关问题