Node file statistics

How to use Node to get detailed information of a file

Each file comes with a set of detailed information that we can view with Node.

In particular, usestat()Provided methodfsModule.

You call it the file path. Once Node gets the file details, it will call the callback function you passed, which contains 2 parameters: error message and file statistics:

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 synchronization method that will block the thread until the file status is ready:

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

The file information is contained in the stats variable. What information can we use these statistics to extract?

Many, including:

  • If the file is a directory or file, usestats.isFile()withstats.isDirectory()
  • If the file is a symbolic link, usestats.isSymbolicLink()
  • File size (in bytes)stats.size.

There are other advanced methods, but most of the methods you will use in everyday programming are like this.

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 })

Download mine for freeNode.js manual


More node tutorials: