// 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; | |
}; |
Just another implementation
const path = require('path');
const fs = require('fs');
/* Prepend the given path segment */
const prependPathSegment = pathSegment => location => path.join(pathSegment, location);
/* fs.readdir but with relative paths */
const readdirPreserveRelativePath = location => fs.readdirSync(location).map(prependPathSegment(location));
/* Recursive fs.readdir but with relative paths */
const readdirRecursive = location => readdirPreserveRelativePath(location)
.reduce((result, currentValue) => fs.statSync(currentValue).isDirectory()
? result.concat(readdirRecursive(currentValue))
: result.concat(currentValue), []);
I think the most elegant way to list all files and/or directories recursively is using globs. You can use globby.
const globby = require('globby');
const listAllFilesAndDirs = dir => globby(`${dir}/**/*`);
(async () => {
const result = await listAllFilesAndDirs(process.cwd());
console.log(result);
})();
@gemyero Great solution, thanks!
mmh Carefull with globby ;)
Here is my way (with typescript):
import fs from "fs/promises";
import path from "path";
export default async function walk(directory: string) {
let fileList: string[] = [];
const files = await fs.readdir(directory);
for (const file of files) {
const p = path.join(directory, file);
if ((await fs.stat(p)).isDirectory()) {
fileList = [...fileList, ...(await walk(p))];
} else {
fileList.push(p);
}
}
return fileList;
}
Alternative solution in Just two lines, Just for fun and learning
const path = ''; // 👈 path to your location
const list = require("child_process").execSync(`cd ${path} && ls -R`).toString().split(`\n`);
Be careful, this solution use a bash script and it works fine in MACOS, for windows or linux could be different
What I use is based on @vidul-nikolaev-petrov version, with a callback argument to do something with files:
const walkSync = (dir, callback) => fs.lstatSync(dir).isDirectory()
? fs.readdirSync(dir).map(f => walkSync(path.join(dir, f), callback))
: callback(dir);
// Note: call to flat at the end to have one array with every paths
const svgs = walkSync(path, fileToBase64).flat()
Alternative solution in Just two lines, Just for fun and learning
const path = ''; // 👈 path to your location const list = require("child_process").execSync(`cd ${path} && ls -R`).toString().split(`\n`);
⚠️ IMPORTANT
Be careful, this solution use a bash script and it works fine in MACOS, for windows or linux could be different
Please, never do that
@FerreiraRaphael kudos
@meowsus Your solution works great, thanks.