Get all files recursively in directories NodejS

node js get all files in directory
node js loop through files in directory
react list files in directory
node get all files in directory with extension
nodejs count files in directory
nodejs walk directory
fs-extra readdir recursive
node readdir is directory

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 like to retrieve the html files of each folder in the folder passed as a parameter. I will explain if I put in parameter "test" I retrieve the files in "test" but I would like to retrieve "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();
                });
            }

The result : [1,2,3]

thanks !

It looks like the glob npm package would help you. Here is an example of how to use it:

File hierarchy:

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

JS code:

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

which displays:

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

Get all files recursively in directories NodejS, Recursively List All the Files in a Directory Using Node. js. Basic Usage of fs.readdirSync() Get All the Files in the Directory. If the item is a directory, we have the function recursively call itself to get all of the files and sub-directories inside the given directory. And if the item is a file, we simply append the file path to the arrayOfFilesarray. When the forEachloop has finished, we return the arrayOfFilesarray.

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

Recursively List All the Files in a Directory Using Node.js, Recursively list all files in a directory and its subdirectories. It does not list the directories themselves. Because it uses fs.readdir, which calls  It lists all files and directories inside a directory recursively and returns an array of objects that each object has two properties: path and stats. path is the full path of the file or directory and stats is an instance of fs.Stats. To install this module, execute the following command in your terminal: npm install klaw-sync

I needed to so something similar, in an Electron app: get all subfolders in a given base folder, using TypeScript, and came up with this:

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

recursive-readdir, recursively find all files in a directory with given extension in node.js. gistfile1.js. var path = require('path'). var fs = require('fs'). function recFindByExt(base,ext  Each directory has txt file with same directory name (means 1.1 will have 1.1.txt file). Let’s start with a simple method to get all files: function getAllFiles (dirPath) { fs.readdirSync (dirPath).forEach (function (file) { let filepath = path.join (dirPath , file); let stat= fs.statSync (filepath); if (stat.isDirectory ()) { getAllFiles (filepath); } else { console.info (filepath+ ' '); } }); } getAllFiles ('./temp');

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.

recursively find all files in a directory with given extension in node.js , Either to create some kind of file search algorithm or to get a list of all the files and folders inside a directory to compress it with zlib, this feature  For each item in the files array, we check whether or not the item is a file or a sub-directory. If the item is a sub-directory, we have the function recursively call itself with removeDir(), with the path of the sub-directory as a parameter. That function will loop through the sub-directory and remove it's children files and directories.

You can also write your own code like below to traverse the directory as shown below :

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

You can check more information about it here : http://www.codingdefined.com/2014/09/how-to-navigate-through-directories-in.html

How to read recursively a directory in Node.js, List all files in a directory recursively, and do something on each. const fs = require('fs'), path = require('path');function walkDir(dir, callback) { fs. node.js getting files from a directory including sub-directories The node.js code snippet below walks through all the directories in the provided directory and returns all the files specified in the fileTypes.

NodeJS Walk Directory - Allen Kim, Get files recursive with the Node.js File System (FS) subdirectory, we are able to get all files within the current directory and all subdirectories. For example, search the current working directory for all files (using callbacks): const Filehound = require('filehound'); Filehound.create() .find( (err, files) => { if (err) { return console.error(`error: ${err}`); } console.log(files); // array of files }); Or promises and specifying a specific directory:

Get files recursive with the Node.js File System (FS) - DEV, We already know how to get information from the inode of a file or directory, so if we only need to generated all the entries in a directory and then call fs.stat for each entry. This script will accept the content of the directory. (Without recursion.). I'm trying to get a list of the names of all the files present in a directory using Node.js. Stack Overflow Public questions and recursively get the child

List content of a directory with Node.js, The node.js code snippet below walks through all the directories in the add it to the global array to save the file path, else if it is a directory, recursively call the  return files.reduce((a, f) => a.concat(f), []); In the above function, line 3 gets executed only after the complete execution of line 2 (i.e. when readdir returns ) right ? If yes, then the thread is blocked isn't it ?

Comments
  • super ! it's perfect ! thank you ! :) nom glob it's very good
  • the shortest way i found
  • thanks ! but how send the result in res.send ? please
  • @coco62 Once you get the result inside the function, you can pass that instead of logging it.
  • I had some trouble with typescript+eslint and the flattening of the array in the last lines. So I replaced the last steps by array.reduce. Since we can't post multiline code in comments, here's a single-liner :) export const getFilesRecursively = (rootPath: string) => getAllSubFolders(rootPath).reduce((result, folder) => [...result, ...getFilesInFolder(folder)], [] as string[])