node.js fs.readdir recursive directory search

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

    A. Have a look at the file module. It has a function called walk:

    file.walk(start, callback)

    Navigates a file tree, calling callback for each directory, passing in (null, dirPath, dirs, files).

    This may be for you! And yes, it is async. However, I think you would have to aggregate the full path's yourself, if you needed them.

    B. An alternative, and even one of my favourites: use the unix find for that. Why do something again, that has already been programmed? Maybe not exactly what you need, but still worth checking out:

    var execFile = require('child_process').execFile;
    execFile('find', [ 'somepath/' ], function(err, stdout, stderr) {
      var file_list = stdout.split('\n');
      /* now you've got a list with full path file names */
    });
    

    Find has a nice build-in caching mechanism that makes subsequent searches very fast, as long as only few folder have changed.

提交回复
热议问题