Get all files recursively in directories NodejS

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

    Here's mine. Like all good answers it's hard to understand:

    const isDirectory = path => statSync(path).isDirectory();
    const getDirectories = path =>
        readdirSync(path).map(name => join(path, name)).filter(isDirectory);
    
    const isFile = path => statSync(path).isFile();  
    const getFiles = path =>
        readdirSync(path).map(name => join(path, name)).filter(isFile);
    
    const getFilesRecursively = (path) => {
        let dirs = getDirectories(path);
        let files = dirs
            .map(dir => getFilesRecursively(dir)) // go through each directory
            .reduce((a,b) => a.concat(b), []);    // map returns a 2d array (array of file arrays) so flatten
        return files.concat(getFiles(path));
    };
    

提交回复
热议问题