分析node_modules使用所有的包名和版本号

220 阅读1分钟

由于给银行做项目,使用nodejs作为后端服务,银行要求统计是否使用漏洞的nodejs组件,依赖项太多了,统计起来太费劲,所以写了一个自动读取目录,可以统计nodejs依赖项和版本号的代码。全部代码如下:

const fs = require('fs-extra')
const path = require('path')
const xlsx = require('node-xlsx')

const searchName = 'package.json'
const moduleList = []
async function test() {
  const files = await fs.readdir(path.join(__dirname, 'node_modules'))
  for (const file of files) {
    const stat = await fs.stat(path.join(__dirname, 'node_modules', file))
    if (stat.isDirectory()) {
      await readDir(file)
    } else if (file === searchName) {
      await readJson(file)
    }
  }

  console.log(moduleList)
  const buffer = xlsx.build([
    { name: 'myFirstSheet', data: moduleList }
  ])

  const fileName = '/Users/zhangshuo/Desktop/idea/teamcom-ui-pc/所有依赖.xlsx'
  fs.writeFile(fileName, buffer, function(err) {
    if (err) {
      throw err
    }
  })
}

async function readDir(fileRoot) {
  try {
    const files = await fs.readdir(path.join(__dirname, 'node_modules', fileRoot))
    for (const file of files) {
      const stat = await fs.stat(path.join(__dirname, 'node_modules', fileRoot, file))
      if (file === 'node_modules') {
        continue
      }
      if (stat.isDirectory()) {
        await readDir(path.join(fileRoot, file))
      } else if (file === searchName) {
        await readJson(path.join(fileRoot, file))
      }
    }
  } catch (e) {

  }
}

async function readJson(filePath) {
  try {
    const result = await fs.readJson(path.join(__dirname, 'node_modules', filePath))
    if (result.name && result.version) {
      moduleList.push([result.name, result.version])
    }
  } catch (e) {

  }
}

test()

最后结果输出为excel,解析每个依赖项里面的package.json信息,如果需要更多信息,可以自行添加。