Skip to content

Instantly share code, notes, and snippets.

@dminkovsky
Created March 22, 2021 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dminkovsky/0fcd23853283da7a7295b26c4e783a21 to your computer and use it in GitHub Desktop.
Save dminkovsky/0fcd23853283da7a7295b26c4e783a21 to your computer and use it in GitHub Desktop.
const fs = require('fs');
const {join} = require('path');
module.exports = async function traverseFs(path, onFile) {
const stack = [];
let i = 0;
let files = await readdir(path);
while (i < files.length) {
const file = files[i];
if (file.isDirectory()) {
const nextPath = join(path, file.name);
const nextFiles = await readdir(nextPath);
// Skip empty directories
if (nextFiles.length) {
stack.push({path, files, i});
path = nextPath;
files = nextFiles;
i = 0;
continue;
}
} else {
await onFile(join(path, file.name));
}
if (i === files.length - 1) {
let restore;
do {
restore = stack.pop();
} while (
restore &&
restore.i === restore.files.length - 1
);
if (restore) {
path = restore.path;
files = restore.files;
i = restore.i + 1;
} else {
break;
}
} else {
i++;
}
}
function readdir(path) {
return new Promise((resolve, reject) => {
fs.readdir(
path,
{withFileTypes: true},
(error, files) => {
if (error) {
reject(error);
} else {
resolve(files);
}
},
);
});
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment