Get all directories within directory nodejs

295

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?

This question is tagged with node.js directory

~ Asked on 2013-08-07 19:32:49

The Best Answer is


522

Here's a shorter, syncronous version of this answer that can list all directories (hidden or not) in the current directory:

const { lstatSync, readdirSync } = require('fs')
const { join } = require('path')

const isDirectory = source => lstatSync(source).isDirectory()
const getDirectories = source =>
  readdirSync(source).map(name => join(source, name)).filter(isDirectory)

Update for Node 10.10.0+

We can use the new withFileTypes option of readdirSync to skip the extra lstatSync call:

const { readdirSync } = require('fs')

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

~ Answered on 2014-07-06 08:41:09


112

Thanks to JavaScript ES6 (ES2015) syntax features it's one liner:

Synchronous version

const { readdirSync, statSync } = require('fs')
const { join } = require('path')

const dirs = p => readdirSync(p).filter(f => statSync(join(p, f)).isDirectory())

Asynchronous version for Node.js 10+ (experimental)

const { readdir, stat } = require("fs").promises
const { join } = require("path")

const dirs = async path => {
  let dirs = []
  for (const file of await readdir(path)) {
    if ((await stat(join(path, file))).isDirectory()) {
      dirs = [...dirs, file]
    }
  }
  return dirs
}

~ Answered on 2016-03-02 22:22:45


Most Viewed Questions: