Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all directories within directory nodejs

I was hoping this would be a simple thing, but I cannot find anything out there to do so.

I just want to get all folders/directories within a given folder/directory.

So for example:

<MyFolder>
|- SomeFolder
|- SomeOtherFolder
|- SomeFile.txt
|- SomeOtherFile.txt
|- x-directory

I would expect to get an array of:

["SomeFolder", "SomeOtherFolder", "x-directory"]

Or the above with the path if that was how it was served...

So does anything already exist to do the above?

like image 641
Grofit Avatar asked Aug 07 '13 19:08

Grofit


3 Answers

Promise

import { readdir } from 'fs/promises'

const getDirectories = async source =>
  (await readdir(source, { withFileTypes: true }))
    .filter(dirent => dirent.isDirectory())
    .map(dirent => dirent.name)

Callback

import { readdir } from 'fs'

const getDirectories = (source, callback) =>
  readdir(source, { withFileTypes: true }, (err, files) => {
    if (err) {
      callback(err)
    } else {
      callback(
        files
          .filter(dirent => dirent.isDirectory())
          .map(dirent => dirent.name)
      )
    }
  })

Syncronous

import { readdirSync } from 'fs'

const getDirectories = source =>
  readdirSync(source, { withFileTypes: true })
    .filter(dirent => dirent.isDirectory())
    .map(dirent => dirent.name)
like image 146
Nick McCurdy Avatar answered Oct 19 '22 12:10

Nick McCurdy


List directories using a path.

function getDirectories(path) {
  return fs.readdirSync(path).filter(function (file) {
    return fs.statSync(path+'/'+file).isDirectory();
  });
}
like image 42
Titlacauan Avatar answered Oct 19 '22 11:10

Titlacauan


Recursive solution

I came here in search of a way to get all of the subdirectories, and all of their subdirectories, etc. Building on the accepted answer, I wrote this:

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

function flatten(lists) {
  return lists.reduce((a, b) => a.concat(b), []);
}

function getDirectories(srcpath) {
  return fs.readdirSync(srcpath)
    .map(file => path.join(srcpath, file))
    .filter(path => fs.statSync(path).isDirectory());
}

function getDirectoriesRecursive(srcpath) {
  return [srcpath, ...flatten(getDirectories(srcpath).map(getDirectoriesRecursive))];
}
like image 41
Patrick McElhaney Avatar answered Oct 19 '22 12:10

Patrick McElhaney