Skip to content

Instantly share code, notes, and snippets.

@MichaelFedora
Created June 8, 2019 15:56
Show Gist options
  • Save MichaelFedora/9a3783c670127f6b61f7973f1604c788 to your computer and use it in GitHub Desktop.
Save MichaelFedora/9a3783c670127f6b61f7973f1604c788 to your computer and use it in GitHub Desktop.
fs-extra-size proposal
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