AI Workshop: learn to build apps with AI →
Working with Files: Node file stats

Join the AI Workshop and learn to build real-world apps with AI. A hands-on, practical program to level up your skills.


Every file comes with a set of details that we can inspect using Node.

In particular, using the stat() method provided by the fs module.

Pass a file path; Node calls your callback with two arguments: an error (or null) and the file stats:

const fs = require('fs')
fs.stat('/Users/flavio/test.txt', (err, stats) => {
  if (err) {
    console.error(err)
    return
  }
  // we have access to the file stats in `stats`
})

Node also provides a synchronous method that blocks until the stats are ready:

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

The stats object contains file metadata. You can extract:

  • whether it is a file or directory — stats.isFile(), stats.isDirectory()
  • whether it is a symbolic link — stats.isSymbolicLink()
  • size in bytes — stats.size

Other methods are available; these are the ones you will use most often.

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

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

Lessons in this unit:

0: Introduction
1: How to check if a file exists in Node.js
2: How to create an empty file in Node.js
3: How to get the names of all the files in a folder in Node
4: How to get the last updated date of a file using Node.js
5: How to remove a file with Node.js
6: How to write a JSON object to file in Node.js
7: How to empty a folder in Node.js
8: Working with file descriptors in Node
9: Node File Paths
10: ▶︎ Node file stats
11: Working with folders in Node
12: How to use the Node.js fs module with async/await
13: How to get the current folder in Node
14: How to get the file extension in Node.js from the MIME type
15: How to get the file extension in Node.js
16: How to list files in a folder in Node
17: How to mass rename files in Node.js
18: Node.js get all files in a folder recursively
19: Incrementing multiple folders numbers at once using Node.js
20: Save some text to a file in Node.js