Created
March 14, 2021 17:00
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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