Skip to content

Instantly share code, notes, and snippets.

@narainsagar
Last active January 14, 2022 05:33
Show Gist options
  • Save narainsagar/5cfd315ab38ba363191b63f8ae8b27db to your computer and use it in GitHub Desktop.
Save narainsagar/5cfd315ab38ba363191b63f8ae8b27db 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 human 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.

const fs = require('fs');
function getFileSize(filename) {
  const stats = fs.statSync(filename);
  //console.log('stats', stats);
  const {size} = stats;
  // convert to human readable format.
  const i = Math.floor(Math.log(size) / Math.log(1024));
  return (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + ['B', 'KB', 'MB', 'GB', 'TB'][i];
}
@narainsagar
Copy link
Author

^ fs.statSync(filePath) will return a json object containing file stats like createdAt, modified, size, etc.

@sanchezzzhak
Copy link

replace stats["size"]; with destruction; (When, you want a little modern)

const fs = require('fs');
function getFileSize(filename) {
  let stats = fs.statSync(filename);
  let {size} = stats;
  let i = Math.floor(Math.log(size) / Math.log(1024));
  return (size / Math.pow(1024, i)).toFixed(2) * 1 + ' ' + ['B', 'KB', 'MB', 'GB', 'TB'][i];
}

@narainsagar
Copy link
Author

👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment