Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CanRau/5033761c31376cc78bd9ca78dff0ca95 to your computer and use it in GitHub Desktop.
Save CanRau/5033761c31376cc78bd9ca78dff0ca95 to your computer and use it in GitHub Desktop.
node.js - function to get file and convert the file size in humanly readable format.

node.js - get the filesize in readable format.

This will take filePath as a function parameter and reads the file via fs module and get the file and converts it's size into more humanly readable format.

function getFileSize(filePath) {
  var stats = fs.statSync(filePath);
  // console.log('stats', stats);
  var size = stats["size"];
  // convert it to humanly readable format.
  var i = Math.floor( Math.log(size) / Math.log(1024) );
  return ( size / Math.pow(1024, i) ).toFixed(2) * 1 + ' ' + ['B', 'KB', 'MB', 'GB', 'TB'][i];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment