Get all files recursively in directories NodejS

前端 未结 10 1274
暖寄归人
暖寄归人 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

    const fs = require('fs');
    const path = require('path');
    var filesCollection = [];
    const directoriesToSkip = ['bower_components', 'node_modules', 'www', 'platforms'];
    
    function readDirectorySynchronously(directory) {
        var currentDirectorypath = path.join(__dirname + directory);
    
        var currentDirectory = fs.readdirSync(currentDirectorypath, 'utf8');
    
        currentDirectory.forEach(file => {
            var fileShouldBeSkipped = directoriesToSkip.indexOf(file) > -1;
            var pathOfCurrentItem = path.join(__dirname + directory + '/' + file);
            if (!fileShouldBeSkipped && fs.statSync(pathOfCurrentItem).isFile()) {
                filesCollection.push(pathOfCurrentItem);
            }
            else if (!fileShouldBeSkipped) {
                var directorypath = path.join(directory + '\\' + file);
                readDirectorySynchronously(directorypath);
            }
        });
    }
    
    readDirectorySynchronously('');
    

    This will fill filesCollection with all the files in the directory and its subdirectories (it's recursive). You have the option to skip some directory names in the directoriesToSkip array.

提交回复
热议问题