Skip to content

Instantly share code, notes, and snippets.

@lmammino
Created March 14, 2021 17:00
Show Gist options
  • Select an option

  • Save lmammino/cec89ed8caa2a31a3d48aff7cec46a5d to your computer and use it in GitHub Desktop.

Select an option

Save lmammino/cec89ed8caa2a31a3d48aff7cec46a5d to your computer and use it in GitHub Desktop.
A small example for a script walking through a path to find all files in the folder and nested subfolders. Implemented only using callbacks
import { readdir, stat } from 'fs'
import { join } from 'path'
function listNestedFilesRec (path, state, cb) {
state.ops++
readdir(path, (err, files) => {
state.ops--
if (err) {
return cb(err)
}
for (const f of files) {
const newPath = join(path, f)
state.ops++
stat(newPath, (err, stats) => {
state.ops--
if (err) {
return cb(err)
}
if (stats.isDirectory()) {
// continue recursively
listNestedFilesRec(newPath, state, cb)
} else if (stats.isFile()) {
// add the file to the list of files
state.files.push(newPath)
}
if (state.ops === 0) {
// no more pending operations
return cb(null, state.files)
}
})
}
})
}
export function listNestedFiles (path, cb) {
const state = { files: [], ops: 0 }
listNestedFilesRec(path, state, cb)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment