Node.js file stats

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:

const  = ('node:fs');

.('/Users/joe/test.txt', (, ) => {
  if () {
    .();
  }
  // 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:

const  = ('node:fs');

try {
  const  = .('/Users/joe/test.txt');
} catch () {
  .();
}

The file information is included in the stats variable. What kind of information can we extract using the stats?

A lot, including:

  • if the file is a directory or a file, using stats.isFile() and stats.isDirectory()
  • if 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.

const  = ('node:fs');

.('/Users/joe/test.txt', (, ) => {
  if () {
    .();
    return;
  }

  .(); // true
  .(); // false
  .(); // false
  .(.); // 1024000 //= 1MB
});

You can also use promise-based fsPromises.stat() method offered by the fs/promises module if you like:

const  = ('node:fs/promises');

async function () {
  try {
    const  = await .('/Users/joe/test.txt');
    .(); // true
    .(); // false
    .(); // false
    .(.); // 1024000 //= 1MB
  } catch () {
    .();
  }
}
();

You can read more about the fs module in the official documentation.

Durată de citire
2 min.
Autori
Contribuie
Editează această pagină