Created
June 8, 2019 15:56
fs-extra-size proposal
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
const fs = require('fs-extra'); | |
const path = require('path'); | |
/** | |
* Get's the size of a file or directory. | |
* | |
* @param {string} p The path to the file or directory | |
* @returns {number} | |
*/ | |
function sizeSync(p) { | |
const stat = fs.statSync(p); | |
if(stat.isFile()) | |
return stat.size; | |
else if(stat.isDirectory()) | |
return fs.readdirSync(p).reduce((a, e) => a + sizeSync(path.join(p, e)), 0); | |
else return 0; // can't take size of a stream/symlink/socket/etc | |
} | |
/** | |
* Get's the size of a file or directory. | |
* | |
* @param {string} p The path to the file or directory | |
* @returns {Promise<number>} | |
*/ | |
async function size(p) { | |
return fs.stat(p).then(stat => { | |
if(stat.isFile()) | |
return stat.size; | |
else if(stat.isDirectory()) | |
return fs.readdir(p) | |
.then(entries => Promise.all(entries.map(e => size(path.join(p, e))))) | |
.then(e => e.reduce((a, c) => a + c, 0)); | |
else return 0; // can't take size of a stream/symlink/socket/etc | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment