Skip to main content
Every file comes with a set of details that we can inspect using Node.js. In particular, using the stat() method provided by the fs module. You call it passing a file path, and once Node.js gets the file details it will call the callback function you pass, with 2 parameters: an error message, and the file stats:
import fs from 'node:fs';

fs.stat('/Users/joe/test.txt', (err, stats) => {
  if (err) {
    console.error(err);
  }
  // we have access to the file stats in `stats`
});
Node.js also provides a sync method, which blocks the thread until the file stats are ready:
import fs from 'node:fs';

try {
  const stats = fs.statSync('/Users/joe/test.txt');
} catch (err) {
  console.error(err);
}

What information is available

The file information is included in the stats variable. A lot is available, including:
  • Whether the file is a directory or a file, using stats.isFile() and stats.isDirectory()
  • Whether the file is a symbolic link using stats.isSymbolicLink()
  • The file size in bytes using stats.size
There are other advanced methods, but the bulk of what you’ll use in your day-to-day programming is this.
import fs from 'node:fs';

fs.stat('/Users/joe/test.txt', (err, stats) => {
  if (err) {
    console.error(err);
    return;
  }

  stats.isFile(); // true
  stats.isDirectory(); // false
  stats.isSymbolicLink(); // false
  console.log(stats.size); // 1024000 //= 1MB
});

Using the promise-based API

You can also use the promise-based fsPromises.stat() method offered by the fs/promises module:
import fs from 'node:fs/promises';

try {
  const stats = await fs.stat('/Users/joe/test.txt');
  stats.isFile(); // true
  stats.isDirectory(); // false
  stats.isSymbolicLink(); // false
  console.log(stats.size); // 1024000 //= 1MB
} catch (err) {
  console.log(err);
}
You can read more about the fs module in the official documentation.

Build docs developers (and LLMs) love