0
0
NodejsHow-ToBeginner · 3 min read

How to Get File Size in Node.js: Simple Guide

In Node.js, you can get a file's size by using fs.stat or fs.promises.stat to read the file's metadata, then accessing the size property from the returned stats object. This gives the file size in bytes.
📐

Syntax

Use fs.stat(path, callback) for asynchronous callback style or fs.promises.stat(path) for promise-based async/await style. Both return a stats object containing file info including size.

  • path: string path to the file
  • callback: function with error and stats parameters
  • stats.size: file size in bytes
javascript
const fs = require('fs');

// Callback style
fs.stat('file.txt', (err, stats) => {
  if (err) {
    console.error(err);
    return;
  }
  console.log(`File size: ${stats.size} bytes`);
});

// Promise style
(async () => {
  try {
    const stats = await fs.promises.stat('file.txt');
    console.log(`File size: ${stats.size} bytes`);
  } catch (err) {
    console.error(err);
  }
})();
💻

Example

This example shows how to get the size of a file named example.txt asynchronously using promises and logs the size in bytes.

javascript
import fs from 'fs/promises';

async function getFileSize(filePath) {
  try {
    const stats = await fs.stat(filePath);
    console.log(`Size of '${filePath}': ${stats.size} bytes`);
  } catch (error) {
    console.error(`Error reading file size: ${error.message}`);
  }
}

getFileSize('example.txt');
Output
Size of 'example.txt': 1234 bytes
⚠️

Common Pitfalls

Common mistakes include:

  • Using synchronous fs.statSync in performance-critical code, which blocks the event loop.
  • Not handling errors when the file does not exist or is inaccessible.
  • Confusing stats.size with file content length in characters; size is in bytes.
javascript
const fs = require('fs');

// Wrong: ignoring errors
fs.stat('nofile.txt', (err, stats) => {
  if (err) {
    console.error('File not found or inaccessible');
    return;
  }
  console.log(`File size: ${stats.size} bytes`);
});

// Right: handle errors
fs.stat('nofile.txt', (err, stats) => {
  if (err) {
    console.error('File not found or inaccessible');
    return;
  }
  console.log(`File size: ${stats.size} bytes`);
});
📊

Quick Reference

Summary tips for getting file size in Node.js:

  • Use fs.promises.stat with async/await for clean code.
  • Always handle errors to avoid crashes.
  • stats.size returns size in bytes, not characters.
  • For large files, avoid synchronous methods to keep your app responsive.

Key Takeaways

Use fs.promises.stat or fs.stat to get file metadata including size.
Always handle errors when accessing file stats to avoid crashes.
The size property is in bytes, not characters or kilobytes.
Prefer asynchronous methods to keep Node.js responsive.
Synchronous methods block the event loop and should be avoided in most cases.