Learn how to check file size in Node.js using built-in modules like fs and fs.promises. This guide covers synchronous and asynchronous methods with code examples.

When working with files in Node.js, itβs often useful to determine the size of a file β whether for validation, logging, or to enforce upload/download limits. Node.js provides built-in modules to retrieve file metadata, including size, using simple and efficient methods.
In this post, weβll explore different ways to get the size of a file in Node.js using:
fs.statSync
(synchronous)fs.promises.stat
(async/await)fs.stat
(callback-based)
π Prerequisites
Ensure you have Node.js installed:
node -v
Create a sample file for testing:
echo "Hello, Node.js file size check!" > test.txt
π Method 1: Using fs.statSync()
(Synchronous)
If you’re working in a script or CLI tool where blocking I/O is acceptable:
const fs = require('fs');
const stats = fs.statSync('test.txt');
console.log(`File size: ${stats.size} bytes`);
π
stats.size
gives the size of the file in bytes.
π Method 2: Using fs.promises.stat()
(Async/Await)
For non-blocking applications, especially servers or services:
const fs = require('fs').promises;
async function getFileSize(filePath) {
try {
const stats = await fs.stat(filePath);
console.log(`File size: ${stats.size} bytes`);
} catch (err) {
console.error('Error getting file size:', err);
}
}
getFileSize('test.txt');
β³ Method 3: Using fs.stat()
with Callbacks
If you’re using traditional Node.js callback patterns:
const fs = require('fs');
fs.stat('test.txt', (err, stats) => {
if (err) {
return console.error('Error:', err);
}
console.log(`File size: ${stats.size} bytes`);
});
π¦ Bonus: Convert Bytes to KB/MB
To display the size in kilobytes or megabytes:
const fileSizeInKB = (bytes) => (bytes / 1024).toFixed(2);
const fileSizeInMB = (bytes) => (bytes / (1024 * 1024)).toFixed(2);
Example:
console.log(`Size: ${fileSizeInKB(stats.size)} KB`);
console.log(`Size: ${fileSizeInMB(stats.size)} MB`);
π§ Use Cases
- Validating file upload limits
- Logging file statistics
- Monitoring disk usage
- Caching file size in services
π§ͺ Conclusion
Node.js makes it easy to retrieve file sizes using its core fs
module. Depending on your application type (CLI, API server, async service), choose the appropriate method:
Method | Use Case |
---|---|
fs.statSync | Simple scripts, CLI tools |
fs.promises.stat | Modern apps with async/await |
fs.stat | Legacy apps or callback patterns |