在目录NodejS中递归获取所有文件

时间:2017-01-04 11:22:41

标签: node.js fs getfiles

我的功能有点问题。我想在许多目录中获取所有文件。目前,我可以检索传入参数的文件中的文件。我想检索作为参数传递的文件夹中每个文件夹的html文件。我将解释如果我输入参数“test”我在“test”中检索文件,但我想检索“test / 1 / * .html”,“test / 2 / ./ 。 html“:

var srcpath2 = path.join('.', 'diapo', result);
function getDirectories(srcpath2) {
                return fs.readdirSync(srcpath2).filter(function (file) {
                    return fs.statSync(path.join(srcpath2, file)).isDirectory();
                });
            }

结果: [1,2,3]

谢谢!

16 个答案:

答案 0 :(得分:20)

看起来glob npm package可以帮到你。以下是如何使用它的示例:

文件层次结构:

test
├── one.html
└── test-nested
    └── two.html

JS代码:

var getDirectories = function (src, callback) {
  glob(src + '/**/*', callback);
};
getDirectories('test', function (err, res) {
  if (err) {
    console.log('Error', err);
  } else {
    console.log(res);
  }
});

显示:

[ 'test/one.html',
  'test/test-nested',
  'test/test-nested/two.html' ]

答案 1 :(得分:7)

我已经看到了很多很长的答案,这有点浪费存储空间。有些人还使用glob之类的软件包,但是如果您不想依赖任何软件包,这是我的解决方案。

const Path = require("path");
const FS   = require("fs");
let Files  = [];

function ThroughDirectory(Directory) {
    FS.readdirSync(Directory).forEach(File => {
        const Absolute = Path.join(Directory, File);
        if (FS.statSync(Absolute).isDirectory()) return ThroughDirectory(Absolute);
        else return Files.push(Absolute);
    });
}

ThroughDirectory("./input/directory/");

这很不言自明。有一个输入目录,并在其中进行遍历。如果其中一项也是目录,请依次浏览,依此类推。如果是文件,则将绝对路径添加到数组。

希望这对您有所帮助:]

答案 2 :(得分:4)

我真的很喜欢 Smally 的解决方案,但不喜欢语法。

相同的解决方案,但更容易阅读:

const fs = require("fs");
const path = require("path");
let files = [];

const getFilesRecursively = (directory) => {
  const filesInDirectory = fs.readdirSync(directory);
  for (const file of filesInDirectory) {
    const absolute = path.join(directory, file);
    if (fs.statSync(absolute).isDirectory()) {
        getFilesRecursively(absolute);
    } else {
        files.push(absolute);
    }
  }
};

答案 3 :(得分:3)

我需要在Electron应用程序中使用类似的东西:使用TypeScript获取给定基本文件夹中的所有子文件夹,然后提出:

import { readdirSync, statSync, existsSync } from "fs";
import * as path from "path";

// recursive synchronous "walk" through a folder structure, with the given base path
getAllSubFolders = (baseFolder, folderList = []) => {

    let folders:string[] = readdirSync(baseFolder).filter(file => statSync(path.join(baseFolder, file)).isDirectory());
    folders.forEach(folder => {
        folderList.push(path.join(baseFolder,folder));
        this.getAllSubFolders(path.join(baseFolder,folder), folderList);
    });
}

答案 4 :(得分:2)

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('');

这将填充 filesCollection 以及目录及其子目录中的所有文件(它是递归的)。您可以选择跳过 directoriesToSkip 数组中的某些目录名称。

答案 5 :(得分:2)

打包到库中: https://www.npmjs.com/package/node-recursive-directory

https://github.com/vvmspace/node-recursive-directory

文件列表:

const getFiles = require('node-recursive-directory');

(async () => {
    const files = await getFiles('/home');
    console.log(files);
})()

具有已解析数据的文件列表:

const getFiles = require('node-resursive-directory');
 
(async () => {
    const files = await getFiles('/home', true); // add true
    console.log(files);
})()

您将获得类似的内容:

  [
      ...,
      {
        fullpath: '/home/vvm/Downloads/images/Some/Some Image.jpg',
        filepath: '/home/vvm/Downloads/images/Some/',
        filename: 'Some Image.jpg',
        dirname: 'Some'
    },
  ]

答案 6 :(得分:1)

这是我的。像所有好的答案一样,很难理解:

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));
};

答案 7 :(得分:1)

使用 ES6 产量

const fs = require('fs');
const path = require('path');

function *walkSync(dir) {
  const files = fs.readdirSync(dir, { withFileTypes: true });
  for (let i = 0; i < files.length; i++) {
    if (file[i].isDirectory()) {
      yield* walkSync(path.join(dir, file[i].name));
    } else {
      yield path.join(dir, file[i].name);
    }
  }
}

for (let i of walkSync(__dirname)) {
  console.log(i);
}

答案 8 :(得分:0)

您也可以编写自己的代码,如下所示遍历目录,如下所示:

var fs = require('fs');
function traverseDirectory(dirname, callback) {
  var directory = [];
  fs.readdir(dirname, function(err, list) {
    dirname = fs.realpathSync(dirname);
    if (err) {
      return callback(err);
    }
    var listlength = list.length;
    list.forEach(function(file) {
      file = dirname + '\\' + file;
      fs.stat(file, function(err, stat) {
        directory.push(file);
 if (stat && stat.isDirectory()) {
          traverseDirectory(file, function(err, parsed) {
     directory = directory.concat(parsed);
     if (!--listlength) {
       callback(null, directory);
     }
   });
 } else {
     if (!--listlength) {
       callback(null, directory);
     }
          }
      });
    });
  });
}
traverseDirectory(__dirname, function(err, result) {
  if (err) {
    console.log(err);
  }
  console.log(result);
});

您可以在此处查看有关此内容的更多信息:http://www.codingdefined.com/2014/09/how-to-navigate-through-directories-in.html

答案 9 :(得分:0)

我的打字稿确实很容易理解

    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);
    };

答案 10 :(得分:0)

使用现代JavaScript(NodeJs 10),您可以使用异步生成器功能并使用for-await...of遍历它们

// ES modules syntax that is included by default in NodeJS 14.
// For earlier versions, use `--experimental-modules` flag
import fs from "fs/promises"

// or, without ES modules, use this:
// const fs = require('fs').promises

async function run() {
  for await (const file of getFiles()) {
    console.log(file.path)
  }
}

async function* getFiles(path = `./`) {
  const entries = await fs.readdir(path, { withFileTypes: true })

  for (let file of entries) {
    if (file.isDirectory()) {
      yield* getFiles(`${path}${file.name}/`)
    } else {
      yield { ...file, path: path + file.name }
    }
  }
}

run()

答案 11 :(得分:0)

您可以使用循环遍历根文件夹的所有文件和目录(如果是目录),则进入其中并重复该过程。 考虑下面的代码:

const fs = require('fs');
const path = require('path');

const target = './'; // choose the directory to target
var result = []
var filePaths = []
var tempFolder = []
const targetPath = fs.readdirSync(target);




function hit(mainPath = targetPath) {

  mainPath.forEach((file) => {

    let check = fs.statSync(file);

    if (!check.isDirectory()) {
      filePaths.push(file)
    }
    else {
      if (file[0] != '.') {
        tempFolder.push(file)
      }
    }
  });

  // get files from folder
  if (tempFolder.length > 0) {
    tempFolder.forEach((dir) => {
      getFiles(dir)
    })
  } 
   // filePaths contains path to every file

}




function getFiles(dir) {

  var paths = fs.readdirSync(dir);
  var files = [];

  paths.forEach(function (file) {
    var fullPath = dir + '/' + file;
    files.push(fullPath);
  });

  files.forEach((tempFile) => {
    let check = fs.statSync(tempFile);

    if (check.isDirectory()) {
      getFiles(tempFile)
    } else {
      filePaths.push(tempFile)
    }
  })
}



hit(); // main function

答案 12 :(得分:0)

如果您更愿意与 glob 同步工作,请使用 documentation 中提到的 glob.sync() 函数。这是@Paul Mougel 提供但同步编写的等效示例:

const glob = require("glob");

var getDirectories = function (src) {
  return glob.sync(src + '/**/*');
};
var rest = getDirectories('test');
console.log(res);

答案 13 :(得分:0)

这是一个紧凑的纯函数,它返回目录中的所有路径(亲戚)。

const getFilesPathsRecursively = (directory: string, origin?: string): string[] =>
  fs.readdirSync(directory).reduce((files, file) => {
    const absolute = path.join(directory, file)
    return [
      ...files,
      ...(fs.statSync(absolute).isDirectory()
        ? getFilesPathsRecursively(absolute, origin || directory)
        : [path.relative(origin || directory, absolute)]),
    ]
  }, [])

答案 14 :(得分:0)

基于 globby 的 Promise 解决方案:

import { globby } from 'globby';

(async () => {
  const path = '/path/to/dir';
  const files = await globby([`${path}/**/*`]);

  console.log(files);
  // [ 
  //   '/path/to/dir/file1.txt', 
  //   '/path/to/dir/subdir/file2.txt', 
  //   ... 
  // ]
})()

答案 15 :(得分:0)

说到 npm 包 - 另一个简短的选择是使用 fs-readdir-recursive

const read = require("fs-readdir-recursive");
const foundFiles = read("test");
console.log(foundFiles);

输出:

[ 'one.html', 'test-nested/some_text.txt', 'test-nested/two.html' ]

如果您只对具有特定扩展名的文件(如问题中提到的 .html)感兴趣,您可以使用 .endsWith() 过滤它们:

const filteredFiles = read("test").filter(item => item.endsWith(".html"));