Skip to content

Instantly share code, notes, and snippets.

@paruljain
Created May 7, 2019 20:24
Show Gist options
  • Save paruljain/523871a2cc0dee69b83bad3f542f229c to your computer and use it in GitHub Desktop.
Save paruljain/523871a2cc0dee69b83bad3f542f229c to your computer and use it in GitHub Desktop.
'use strict'
const fs = require('fs'),
path = require('path')
exports.scan = function(folder) {
if (!folder) return
const stats = fs.statSync(folder)
if (!stats.isDirectory()) throw new Error(`${folder} is not a directory`)
const self = this
const files = []
let filesScanned = 0
let bytesScanned = 0
const startTime = Date.now()
let wg = 0
function d(p) {
wg++
fs.readdir(p, (err, entries) => {
if (err) throw err
for (const entry of entries) {
const fullPath = path.join(p, entry)
wg++
fs.stat(fullPath, (err, stats) => {
if (err) throw err
if (stats.isDirectory()) {d(fullPath); done()}
else done(stats)
})
}
done()
})
}
function done(stats) {
wg--
if (stats) {
filesScanned++
bytesScanned += stats.size
}
if (!wg) {
const timeTaken = Math.ceil((Date.now() - startTime)/1000)
console.log(`Scanned ${filesScanned} files, ${bytesScanned} bytes in ${timeTaken} seconds`)
return
}
}
d(folder)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment