node.js fs.readdir recursive directory search

前端 未结 30 1538
醉酒成梦
醉酒成梦 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:22

    For fun, here is a flow based version that works with highland.js streams library. It was co-authored by Victor Vu.

    ###
      directory >---m------> dirFilesStream >---------o----> out
                    |                                 |
                    |                                 |
                    +--------< returnPipe <-----------+
    
      legend: (m)erge  (o)bserve
    
     + directory         has the initial file
     + dirListStream     does a directory listing
     + out               prints out the full path of the file
     + returnPipe        runs stat and filters on directories
    
    ###
    
    _ = require('highland')
    fs = require('fs')
    fsPath = require('path')
    
    directory = _(['someDirectory'])
    mergePoint = _()
    dirFilesStream = mergePoint.merge().flatMap((parentPath) ->
      _.wrapCallback(fs.readdir)(parentPath).sequence().map (path) ->
        fsPath.join parentPath, path
    )
    out = dirFilesStream
    # Create the return pipe
    returnPipe = dirFilesStream.observe().flatFilter((path) ->
      _.wrapCallback(fs.stat)(path).map (v) ->
        v.isDirectory()
    )
    # Connect up the merge point now that we have all of our streams.
    mergePoint.write directory
    mergePoint.write returnPipe
    mergePoint.end()
    # Release backpressure.  This will print files as they are discovered
    out.each H.log
    # Another way would be to queue them all up and then print them all out at once.
    # out.toArray((files)-> console.log(files))
    

提交回复
热议问题