Node.js – How to get File Size in KB, MB and GB

  • by
node-js-how-to-get-file-size-in-bytes-kb-mb-gb

In this tutorial we will see how to get file size in different formats like bytes, KB, MB & GB in Node.js. To get size of a file in Node.js we can use built-in module fs function fs.stat(), this function provides different file properties values out of which one is file size.

Example: How to get File size –

const fs = require("fs")

let filePath = './media/video/video1.mkv';
fs.stat(filePath, (error,stats)=>{
if(error)
{console.log(error);
return;
}

let fileSize = stats.size;
let fileSizeKB = roundOff(fileSize*0.001);
let fileSizeMB = roundOff(fileSizeKB*0.001);
let fileSizeGB = roundOff(fileSizeMB*0.001);

console.log("File sizes: ");
console.log(fileSize +" Bytes");
console.log(fileSizeKB +"KB");
console.log(fileSizeMB +"MB");
console.log(fileSizeGB +"GB");

});

function roundOff(value)
{
return Math.round(value*100)/100;
}

In the example code, filePath specifies the path of the file which is inside media>video folder and the file name is video1.mkv i.e. it is a media file.  fs.stat() function accepts two parameters, path – file path and a callback function which returns the stats i.e. properties of a file and a error object if any error occurs in the process.

The roundOff() function is for rounding off the decimal values. The fs.stat() function give us size of the file in bytes, so it is necessary to convert the values into more common formats i.e. Kilobytes – KB, Megabytes – MB, Gigabyes – GB. You can go on with more formats as per your requirements.

DOWNLOAD SOURCE CODE

Output of the above code:

PS C:\Code\Node\fileSystem> node file-size.js
File sizes:
1948304043 Bytes
1948304.04KB
1948.3MB
1.95GB
PS C:\Code\Node\fileSystem>

Error output incase file isn’t found or available:

PS C:\Code\Node\fileSystem> node file-size.js
[Error: ENOENT: no such file or directory, stat 'C:\Code\Node\fileSystem\media\video\video1.mkv'] {
errno: -4058,
code: 'ENOENT',
syscall: 'stat',
path: 'C:\\Code\\Node\\fileSystem\\media\\video\\video1.mkv'
}
PS C:\Code\Node\fileSystem>

Code Snapshot:

node-js-how-to-get-file-size-in-bytes-kb-mb-gb

DOWNLOAD SOURCE CODE

More on Node.js:

Check if a directory exists in Node.js

How to rename a file in Node.js

Renaming a folder or a directory in Node.js

How to create directory using Node.js

Node.js – Create, read and write text files.

HTTP module in Node.js

Install Node.js on Windows.

Node.js – How to create PDF documents.


2