Last updated: Apr 5, 2024
Reading timeยท5 min
To get the size of a file in Node.js:
fs.statSync()
method to get a stats object.size
property on the stats
object to get the size of the file
in bytes.1024 * 1024
.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); }
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.
// ๐๏ธ 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.
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 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.
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 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.
If you need to get the size of a file asynchronously in Node.js, import fs
from the fs/promises
module.
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); });
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.
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.
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); }
Make sure your environment supports top-level await
to be able to run the code
sample.
You can also use the callback-style syntax to get the size of a file in Node.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 });
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.
filesize
NPM packageYou 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.
npm install filesize yarn add filesize
Now import and use the module as follows.
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); }
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.
You can learn more about the related topics by checking out the following tutorials: