Get all files recursively in directories NodejS

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

    I did mine with typescript works well fairly easy to understand

        import * as fs from 'fs';
        import * as path from 'path';
    
        export const getAllSubFolders = (
          baseFolder: string,
          folderList: string[] = []
        ) => {
          const folders: string[] = fs
            .readdirSync(baseFolder)
            .filter(file => fs.statSync(path.join(baseFolder, file)).isDirectory());
          folders.forEach(folder => {
            folderList.push(path.join(baseFolder, folder));
            getAllSubFolders(path.join(baseFolder, folder), folderList);
          });
          return folderList;
        };
        export const getFilesInFolder = (rootPath: string) => {
          return fs
            .readdirSync(rootPath)
            .filter(
              filePath => !fs.statSync(path.join(rootPath, filePath)).isDirectory()
            )
            .map(filePath => path.normalize(path.join(rootPath, filePath)));
        };
        export const getFilesRecursively = (rootPath: string) => {
          const subFolders: string[] = getAllSubFolders(rootPath);
          const allFiles: string[][] = subFolders.map(folder =>
            getFilesInFolder(folder)
          );
          return [].concat.apply([], allFiles);
        };
    

提交回复
热议问题