A pattern for recursion with Promises - in this example, walking a directory structure.
readDirRecursive()
is called with a starting directory and will itself return aPromise
.- Internally
readDir()
is called and passed starting directory to read from. - A list of directory items is returned by
getItemList()
as aPromise
, which in turn is chained togetItemListStat()
to stat each item to determine if file or directory. - Finalised list then passed to
processItemList()
:- Files are added to accumulating
fileList
array. - Directories are added to
readDirQueue
. - If directories exist on
readDirQueue
, next directory is shifted off to anotherreadDir()
call and returned to parentPromise
(this is the recursion).
- Files are added to accumulating
- Process continues until
readDirQueue
is exhausted at which point the finalPromise
will resolve by returning accumulatedfileList
fromreadDirRecursive()
.
$ nodejs readdirrecursive.js
[ '/path/to/README.md',
'/path/to/readdirrecursive.js',
'/path/to/.git/COMMIT_EDITMSG',
'/path/to/.git/HEAD',
'/path/to/.git/config',
'/path/to/.git/description',
'/path/to/.git/index',
'/path/to/.git/packed-refs',
'/path/to/.git/hooks/applypatch-msg.sample',
'/path/to/.git/hooks/commit-msg.sample',
'/path/to/.git/hooks/post-update.sample',
'/path/to/.git/hooks/pre-applypatch.sample',
'/path/to/.git/hooks/pre-commit.sample',
'/path/to/.git/hooks/pre-push.sample',
'/path/to/.git/hooks/pre-rebase.sample',
'/path/to/.git/hooks/pre-receive.sample',
'/path/to/.git/hooks/prepare-commit-msg.sample',
'/path/to/.git/hooks/update.sample',
'/path/to/.git/info/exclude',
'/path/to/.git/info/refs',
'/path/to/.git/logs/HEAD',
'/path/to/.git/objects/e6/9de29bb2d1d6434b8b29ae775ad8c2e48c5391',
'/path/to/.git/objects/info/packs',
'/path/to/.git/objects/pack/pack-d781ac0f9e797c9aa5683e5071e8db3f7af8e5f8.idx',
'/path/to/.git/objects/pack/pack-d781ac0f9e797c9aa5683e5071e8db3f7af8e5f8.pack',
'/path/to/.git/logs/refs/heads/master',
'/path/to/.git/refs/remotes/origin/HEAD',
'/path/to/.git/logs/refs/remotes/origin/HEAD',
'/path/to/.git/logs/refs/remotes/origin/master' ]
This line seems to be significant but I'm not clear if
path.resolve
is a method native to path and not the resolve executor of Promise. I'm not familiar with the details of usingrequire
to import modules.