How to Get File Size in Node.js: Methods & Best Practices

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:

MethodUse Case
fs.statSyncSimple scripts, CLI tools
fs.promises.statModern apps with async/await
fs.statLegacy apps or callback patterns

πŸ”— Further Reading

Leave a Reply