How to get the size of a file in Node.js

To get the size of a file in Node.js, you can use the stat() method provided by the built-in fs module. This method works asynchronously and lists the statistics of a file at the given path.

All you need to do is pass in the file path and a callback function to the fs.stat() method. Once the file statistics are populated by Node.js, it will invoke the callback function with two arguments: an error message and the file stats:

const fs = require('fs')

// Read file stats
fs.stat('file.txt', (err, stats) => {
  if (err) {
    console.log(`File doesn't exist.`)
  } else {
    console.log(stats)
  }
})

The stats object returned by the fs.stat() function looks like the following:

Stats {
  dev: 16777221,
  mode: 33279,
  nlink: 1,
  uid: 501,
  gid: 20,
  rdev: 0,
  blksize: 4096,
  ino: 5172976,
  size: 290,
  blocks: 8,
  atimeMs: 1606143471354.2327,
  mtimeMs: 1599218860000,
  ctimeMs: 1606074010041.4927,
  birthtimeMs: 1605423684000,
  atime: 2020-11-23T14:57:51.354Z,
  mtime: 2020-09-04T11:27:40.000Z,
  ctime: 2020-11-22T19:40:10.041Z,
  birthtime: 2020-11-15T07:01:24.000Z
}

To get the size of the file, you can use the size property in the stats object:

const size = stats.size; // 290 bytes

The size of the file is returned in bytes. You can convert it into a human-readable format to display publicly.

The fs module also provides a synchronous variant of stat() called statSync() that blocks the execution of the Node.js event loop until the file statistics are ready:

try {
  const stats = fs.statSync('file.txt')
} catch (err) {
  console.log(err)
}

The fs.stat() method can also be used to check if the path is a file, a directory, or a symbolic link, as shown below:

const fs = require('fs')

// Read file stats
fs.stat('file.txt', (err, stats) => {
  if (err) {
    console.log(`File doesn't exist.`)
    return
  }

  console.log(stats.isFile()) // true
  console.log(stats.isDirectory()) // false
  console.log(stats.isSymbolicLink()) // false
})

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.