Skip to content

Instantly share code, notes, and snippets.

@monochromer monochromer/index.js

Last active Jul 27, 2020
Embed
What would you like to do?
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
You can’t perform that action at this time.