node.js fs.readdir recursive directory search

前端 未结 30 2012
醉酒成梦
醉酒成梦 2020-11-22 15:55

Any ideas on an async directory search using fs.readdir? I realise that we could introduce recursion and call the read directory function with the next directory to read, bu

30条回答
  •  半阙折子戏
    2020-11-22 16:10

    Async

    const fs = require('fs')
    const path = require('path')
    
    const readdir = (p, done, a = [], i = 0) => fs.readdir(p, (e, d = []) =>
      d.map(f => readdir(a[a.push(path.join(p, f)) - 1], () =>
        ++i == d.length && done(a), a)).length || done(a))
    
    readdir(__dirname, console.log)
    

    Sync

    const fs = require('fs')
    const path = require('path')
    
    const readdirSync = (p, a = []) => {
      if (fs.statSync(p).isDirectory())
        fs.readdirSync(p).map(f => readdirSync(a[a.push(path.join(p, f)) - 1], a))
      return a
    }
    
    console.log(readdirSync(__dirname))
    

    Async readable

    function readdir (currentPath, done, allFiles = [], i = 0) {
      fs.readdir(currentPath, function (e, directoryFiles = []) {
        if (!directoryFiles.length)
          return done(allFiles)
        directoryFiles.map(function (file) {
          var joinedPath = path.join(currentPath, file)
          allFiles.push(joinedPath)
          readdir(joinedPath, function () {
            i = i + 1
            if (i == directoryFiles.length)
              done(allFiles)}
          , allFiles)
        })
      })
    }
    
    readdir(__dirname, console.log)
    

    Note: both versions will follow symlinks (same as the original fs.readdir)

提交回复
热议问题