Notes

JavaScript - Get all files in a directory

author: Paul Kim

categories: js

tags: js

JavaScript - Get all files in a directory

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

// List all files in a directory in Node.js recursively in a synchronous fashion
// https://gist.github.com/kethinov/6658166

const testFolder = './src/private-pages'

// return array of all files in a directory (recursive, synchronous)
const walkSync = (dir, fileList = []) => {
  const files = fs.readdirSync(dir)
  files.forEach((file) => {
    const stat = fs.statSync(path.join(dir, file))
    fileList = stat.isDirectory()
      ? walkSync(path.join(dir, file), fileList)
      : fileList.concat(path.join(dir, file))
  })
  return fileList
}
console.log(walkSync(testFolder))

// one liner
const walkSync1 = (d) =>
  fs.statSync(d).isDirectory()
    ? fs.readdirSync(d).map((f) => walkSync(path.join(d, f)))
    : d
console.log(walkSync1(testFolder))

// reduce
const getAllFiles = (dir) =>
  fs.readdirSync(dir).reduce((files, file) => {
    const name = path.join(dir, file)
    const isDirectory = fs.statSync(name).isDirectory()
    return isDirectory ? [...files, ...getAllFiles(name)] : [...files, name]
  }, [])
console.log(getAllFiles(testFolder))

// functional programming approach
const getFilePaths = (folderPath) => {
  const entryPaths = fs
    .readdirSync(folderPath)
    .map((entry) => path.join(folderPath, entry))
  const filePaths = entryPaths.filter((entryPath) =>
    fs.statSync(entryPath).isFile()
  )
  const dirPaths = entryPaths.filter(
    (entryPath) => !filePaths.includes(entryPath)
  )
  const dirFiles = dirPaths.reduce(
    (prev, curr) => prev.concat(getFilePaths(curr)),
    []
  )
  return [...filePaths, ...dirFiles]
}
console.log(getFilePaths(testFolder))

// iterative approach
const walk = (dir) => {
  const result = []
  const files = [dir]
  do {
    const filepath = files.pop()
    const stat = fs.lstatSync(filepath)
    if (stat.isDirectory()) {
      fs.readdirSync(filepath).forEach((f) =>
        files.push(path.join(filepath, f))
      )
    } else if (stat.isFile()) {
      result.push(filepath)
    }
  } while (files.length !== 0)
  return result
}
console.log(walk(testFolder))

ChromeEdgeFirefoxOpera

© 2021 paulkode.com. All rights reserved.