Skip to content

Instantly share code, notes, and snippets.

@kethinov
Created September 22, 2013 09:04
Show Gist options
  • Save kethinov/6658166 to your computer and use it in GitHub Desktop.
Save kethinov/6658166 to your computer and use it in GitHub Desktop.
List all files in a directory in Node.js recursively in a synchronous fashion
// List all files in a directory in Node.js recursively in a synchronous fashion
var walkSync = function(dir, filelist) {
var fs = fs || require('fs'),
files = fs.readdirSync(dir);
filelist = filelist || [];
files.forEach(function(file) {
if (fs.statSync(dir + file).isDirectory()) {
filelist = walkSync(dir + file + '/', filelist);
}
else {
filelist.push(file);
}
});
return filelist;
};
@JESUSrosetolife
Copy link

Hi, here's a modern version:

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

const walk = async (dir, filelist = []) => {
  const files = await fs.readdir(dir);

  for (file of files) {
    const filepath = path.join(dir, file);
    const stat = await fs.stat(filepath);

    if (stat.isDirectory()) {
      filelist = await walk(filepath, filelist);
    } else {
      filelist.push(file);
    }
  }

  return filelist;
}

Here's what I used (needed import)

import * as fs from 'fs/promises';
import path from 'path';

export async function directory_read(dir, filelist = []) {
  const files = await fs.readdir(dir);

  for (let file of files) {
    const filepath = path.join(dir, file);
    const stat = await fs.stat(filepath);

    if (stat.isDirectory()) {
      filelist = await directory_read(filepath, filelist);
    } else {
      filelist.push(file);
    }
  }

  return filelist;
}

@schadocalex
Copy link

schadocalex commented Oct 12, 2023

Node v20.1+

const filelist = await fs.readdir(dir, { recursive: true });

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment