Get all files recursively in directories NodejS

前端 未结 10 1271
暖寄归人
暖寄归人 2020-12-14 07:15

I have a little problem with my function. I would like to get all files in many directories. Currently, I can retrieve the files in the file passed in parameters. I would li

10条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-14 07:21

    With modern JavaScript (NodeJs 10) you can use async generator function and loop through them using for-await...of

    // ES modules syntax that is included by default in NodeJS 14.
    // For earlier versions, use `--experimental-modules` flag
    import fs from "fs/promises"
    
    // or, without ES modules, use this:
    // const fs = require('fs').promises
    
    async function run() {
      for await (const file of getFiles()) {
        console.log(file.path)
      }
    }
    
    async function* getFiles(path = `./`) {
      const entries = await fs.readdir(path, { withFileTypes: true })
    
      for (let file of entries) {
        if (file.isDirectory()) {
          yield* getFiles(`${path}${file.name}/`)
        } else {
          yield { ...file, path: path + file.name }
        }
      }
    }
    
    run()
    

提交回复
热议问题