How to get the Size of a File in Node.js [5 Ways]

avatar
Borislav Hadzhiev

Last updated: Apr 5, 2024
5 min

banner

# Table of Contents

  1. How to get the Size of a File in Node.js
  2. How to get the Size of a File Asynchronously in Node.js
  3. How to get the Size of a File using the callback-style syntax
  4. How to get the Size of a File using the filesize NPM package

# How to get the Size of a File in Node.js

To get the size of a file in Node.js:

  1. Use the fs.statSync() method to get a stats object.
  2. Access the size property on the stats object to get the size of the file in bytes.
  3. Optionally convert the file's size to megabytes by dividing by 1024 * 1024.
index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ If you use CommonJS require() // const fs = require('fs') try { const stats = fs.statSync('./my-file.txt'); const fileSizeInBytes = stats.size; console.log('Size in bytes:', fileSizeInBytes); const fileSizeInMegaBytes = fileSizeInBytes / (1024 * 1024); console.log('Size in MegaBytes:', fileSizeInMegaBytes); } catch (err) { console.log(err.message); }

get size of file in node js

The code for this article is available on GitHub

The fs.statSync method returns an fs.Stats object.

The only argument we passed to the method is the path to the file.

The size property of the stats object returns the size of the file in bytes.

If you need to convert the file size to megabytes, divide the result by 1024 * 1024.

The example above uses the ES6 Modules import/export syntax.

If you use CommonJS require(), use the following import statement instead.

index.js
// ๐Ÿ‘‡๏ธ if you use CommonJS require() const fs = require('fs') // ... rest of the code

If you need to get the size of a file often, create a reusable function.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ If you use CommonJS require() // const fs = require('fs') function getFileSize(filePath) { try { const stats = fs.statSync(filePath); return stats.size; } catch (err) { console.log(err.message); } } console.log(getFileSize('./my-file.txt')); // ๐Ÿ‘‰๏ธ 184029
The code for this article is available on GitHub

The getFileSize function takes a file path as a parameter and returns the size of the file in bytes.

If you need to convert the file size to a human-readable format, use the following function.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ If you use CommonJS require() // const fs = require('fs'); try { const stats = fs.statSync('./my-file.txt'); const fileSizeInBytes = stats.size; const humanReadableFileSize = bytesToSize(fileSizeInBytes); console.log(humanReadableFileSize); // ๐Ÿ‘‰๏ธ 184.03 KB } catch (err) { console.log(err.message); } function bytesToSize(bytes, decimals = 2) { if (!Number(bytes)) { return '0 Bytes'; } const kbToBytes = 1000; const dm = decimals < 0 ? 0 : decimals; const sizes = [ 'Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB', ]; const index = Math.floor( Math.log(bytes) / Math.log(kbToBytes), ); return `${parseFloat( (bytes / Math.pow(kbToBytes, index)).toFixed(dm), )} ${sizes[index]}`; }
The code for this article is available on GitHub

The bytesToSize() function converts bytes to a human-readable format, e.g. 184.03 KB.

I've written a detailed guide on how to convert Bytes to KB, MB, GB or TB in JavaScript.

# How to get the Size of a File Asynchronously in Node.js

If you need to get the size of a file asynchronously in Node.js, import fs from the fs/promises module.

index.js
import fs from 'fs/promises'; // ๐Ÿ‘‡๏ธ If you use CommonJS require() // const fs = require('fs/promises') async function getFileSize(filePath) { try { const stats = await fs.stat(filePath); return stats.size; } catch (err) { console.log(err.message); } } getFileSize('./my-file.txt').then(fileSizeInBytes => { console.log(fileSizeInBytes); });

get size of file asynchronously in node js

The code for this article is available on GitHub

Notice that we import fs from fs/promises.

This enables us to use the async (promisified) equivalent of the fs methods.

The fsPromises.stat method returns a Promise that fulfills with the fs.Stats object for the given file path.

The last step is to access the size property on the Stats object to return the size of the file in bytes.

If your environment supports top-level await, you can also use the following syntax when calling the function.

index.js
import fs from 'fs/promises'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs/promises') async function getFileSize(filePath) { try { const stats = await fs.stat(filePath); return stats.size; } catch (err) { console.log(err.message); } } // ๐Ÿ‘‡๏ธ using top-level await const fileSizeInBytes = await getFileSize('./my-file.txt'); console.log(fileSizeInBytes);

You can also directly call fs.stat() in a try/catch block without calling a function.

index.js
import fs from 'fs/promises'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs/promises') try { const stats = await fs.stat('./my-file.txt'); const fileSizeInBytes = stats.size; console.log(fileSizeInBytes); } catch (err) { console.log(err.message); }
The code for this article is available on GitHub

Make sure your environment supports top-level await to be able to run the code sample.

# How to get the Size of a File using the callback-style syntax

You can also use the callback-style syntax to get the size of a file in Node.js.

index.js
import fs from 'fs'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs'); fs.stat('./my-file.txt', (err, stats) => { if (err) { console.log(err.message); throw err; } const fileSizeInBytes = stats.size; console.log(fileSizeInBytes); // ๐Ÿ‘‰๏ธ 184029 });

get size of file using callback style syntax

The fs.stat() method asynchronously retrieves and returns an fs.Stats object

The callback function we passed to fs.stat gets called with an error (if one occurred) and the stats object.

The last step is to access the size property on the object to get the size of the file in bytes.

# How to get the Size of a File using the filesize NPM package

You can also use the popular filesize npm package to format the file size according to your needs.

Install the package by running the following command from your terminal.

shell
npm install filesize yarn add filesize

Now import and use the module as follows.

index.js
import fs from 'fs/promises'; import {filesize} from 'filesize'; // ๐Ÿ‘‡๏ธ if you use CommonJS require() // const fs = require('fs/promises') // async function getFileSize(filePath) { try { const stats = await fs.stat('./my-file.txt'); const fileSizeInBytes = stats.size; console.log(fileSizeInBytes); // ๐Ÿ‘‰๏ธ 184029 // ๐Ÿ‘‡๏ธ 184.03 kB console.log( filesize(fileSizeInBytes, {base: 10, standard: 'jedec'}), ); // ๐Ÿ‘‡๏ธ 179.72 KB console.log( filesize(fileSizeInBytes, {base: 2, standard: 'jedec'}), ); } catch (err) { console.log(err.message); }

get file size of file using filesize module

The code for this article is available on GitHub

The filesize module provides a simple way to get a human-readable file size string.

By default, the base property in the options object is set to 10, but you can specify a different value if necessary.

You can view more examples of using the filesize module in its NPM page.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev