Skip to content

Instantly share code, notes, and snippets.

@monochromer
Last active July 27, 2020 18:59
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 monochromer/736d857e2955052fac607c4812d1fbe3 to your computer and use it in GitHub Desktop.
Save monochromer/736d857e2955052fac607c4812d1fbe3 to your computer and use it in GitHub Desktop.
Walk directory on node.js without recursion
const path = require('path')
const fs = require('fs').promises
async function walk(fsPath, callback) {
const node = {
path: fsPath,
stat: await fs.stat(fsPath)
}
const stack = [node]
let item
while (item = stack.shift()) {
if (item.stat.isDirectory()) {
const items = await fs.readdir(item.path, {
withFileTypes: true
})
const nodes = items.map(direntItem => ({
stat: direntItem,
path: path.join(item.path, direntItem.name)
}))
stack.push(...nodes)
} else {
callback(item)
}
}
}
(async function main() {
await walk(__dirname, (arg) => console.log(arg.path))
})();
const fs = require('fs').promises;
const path = require('path');
async function* walk(dirPath) {
let item;
const queue = [dirPath];
while (item = queue.shift()) {
const dir = await fs.opendir(item);
for await (const dirent of dir) {
const direntPath = path.join(item, dirent.name);
if (dirent.isDirectory()) {
queue.push(direntPath);
}
yield { dirent, direntPath };
}
}
}
module.exports = walk;
const path = require('path')
const fs = require('fs').promises
async function* walk(fsPath) {
const node = {
path: fsPath,
stat: await fs.stat(fsPath)
}
const stack = [node]
let item
while (item = stack.shift()) {
if (item.stat.isDirectory()) {
const items = await fs.readdir(item.path, {
withFileTypes: true
})
const nodes = items.map(direntItem => ({
stat: direntItem,
path: path.join(item.path, direntItem.name)
}))
stack.push(...nodes)
} else {
yield item
}
}
}
module.exports = walk;
const fs = require('fs');
const path = require('path');
const { promisify } = require('util');
function readDir(path) {
return promisify(fs.readdir)(path, { withFileTypes: true });
}
async function getAllFiles(dirPath, files = []) {
const items = await readDir(dirPath);
for (const dirItem of items) {
const newPath = path.join(dirPath, dirItem.name);
if (dirItem.isDirectory()) {
await getAllFiles(newPath, files);
} else {
files.push(newPath);
}
}
return files;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment