Created
June 30, 2017 15:15
-
-
Save sebbarg/7d66b84ab1017eb6339220a0d9482b3b to your computer and use it in GitHub Desktop.
JS Example of async counting of directories and files.
This file contains 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
#!/usr/bin/env node | |
// | |
// Example of async counting of directories and files. | |
// | |
const fs = require('fs'); | |
const path = require('path'); | |
let walk = function(fileOrDir, done) { | |
let results = { dirCount: 0, fileCount: 0 }; | |
fs.readdir(fileOrDir, function(err, filelist) { | |
if (err) return done(err); | |
let pending = filelist.length; | |
if (pending === 0) return done(null, results); | |
filelist.forEach(function(file) { | |
file = path.resolve(fileOrDir, file); | |
fs.stat(file, function(err, stat) { | |
if (stat && stat.isDirectory()) { | |
console.log(`Walk: ${fileOrDir}`); | |
results.dirCount++; | |
walk(file, function(err, res) { | |
results.dirCount += res.dirCount; | |
results.fileCount += res.fileCount; | |
if (--pending === 0) done(null, results); | |
}); | |
} else { | |
console.log(`file: ${file}`); | |
results.fileCount++; | |
if (--pending === 0) done(null, results); | |
} | |
}); // fs.stat | |
}); // filelist.foreEach | |
}); // fs.readdir | |
}; | |
walk('test', (err, results) => { | |
if (err) | |
console.log('err ' + err); | |
else | |
console.log(`Dirs: ${results.dirCount}, files: ${results.fileCount}`); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment