0
0
NodejsHow-ToBeginner · 3 min read

How to Use fs.stat in Node.js: Syntax and Examples

Use fs.stat(path, callback) in Node.js to get information about a file or directory asynchronously. The callback receives an error and a Stats object with details like size and modification time. For synchronous use, fs.statSync(path) returns the Stats object directly.
📐

Syntax

The fs.stat function checks the status of a file or directory at a given path.

  • path: The file or directory path as a string, Buffer, or URL.
  • callback: A function called with two arguments: an error (if any) and a Stats object.

The Stats object contains properties like size, mtime (modification time), and methods like isFile() and isDirectory().

javascript
fs.stat(path, (err, stats) => {
  if (err) {
    // handle error
  } else {
    // use stats object
  }
});
💻

Example

This example shows how to use fs.stat to check if a file exists and print its size and modification date.

javascript
import { stat } from 'fs';

const filePath = './example.txt';

stat(filePath, (err, stats) => {
  if (err) {
    console.error('Error reading file stats:', err.message);
    return;
  }
  console.log(`File size: ${stats.size} bytes`);
  console.log(`Last modified: ${stats.mtime}`);
  console.log(`Is file: ${stats.isFile()}`);
  console.log(`Is directory: ${stats.isDirectory()}`);
});
Output
File size: 1024 bytes Last modified: 2024-06-01T12:34:56.789Z Is file: true Is directory: false
⚠️

Common Pitfalls

Common mistakes when using fs.stat include:

  • Not handling errors, especially when the file does not exist, which causes err to be set.
  • Confusing fs.stat with fs.lstat, which behaves differently for symbolic links.
  • Using synchronous fs.statSync in performance-critical code, which blocks the event loop.

Always check for errors before using the stats object.

javascript
import { stat } from 'fs';

// Wrong: ignoring error
stat('missing.txt', (err, stats) => {
  console.log(stats.size); // This will throw if err is not checked
});

// Right: check error first
stat('missing.txt', (err, stats) => {
  if (err) {
    console.error('File not found');
    return;
  }
  console.log(stats.size);
});
📊

Quick Reference

Summary of fs.stat usage:

MethodDescription
fs.stat(path, callback)Asynchronously gets file or directory stats.
fs.statSync(path)Synchronously gets file or directory stats.
stats.sizeSize of the file in bytes.
stats.mtimeLast modification date.
stats.isFile()Returns true if path is a file.
stats.isDirectory()Returns true if path is a directory.

Key Takeaways

Always handle errors in the callback to avoid crashes when the file is missing.
Use fs.stat asynchronously to keep your app responsive.
The Stats object provides useful info like size and modification time.
Use stats.isFile() and stats.isDirectory() to check the type.
Avoid blocking the event loop by not using fs.statSync in async code.