Node.js — Get the Size of a File

Node.js ships with the native fs module to interact with the local file system. The fs module supports retrieving statistics for a file on your local disk. You may also get the size of a file from these statistics.

This tutorial shows you how to retrieve the file size in bytes for a given file on your local hard drive.

Node.js Series Overview

Retrieve the File Size in Node.js

The way to retrieve the file size in Node.js is to first get a file’s statistics object, also called “stats”. This stats object contains the size attribute describing the size of the file in bytes.

Here’s the sample code for a fileSize utility method returning the size of a file in bytes:

import Fs from 'fs/promises'

/**
 * Returns the file size of the file located at `path` in bytes.
 *
 * @param {String} path
 *
 * @returns {Number}
 */
async function fileSize (path) {  
  const stats = await Fs.stat(path)

  return stat.size
}

Then you may use the fileSize method like this:

const sizeInBytes = await fileSize('./package.json')  
// 149

Use the @supercharge/fs Package

I’m the maintainer of the @supercharge/fs package providing convenient file system utilities. The @supercharge/fs package comes with a handy Fs.size(path) method returning the size of the file located at path in bytes :

import Fs from '@supercharge/fs'

const sizeInBytes = await Fs.size('./package.json')  
// 1493

That’s it!


Mentioned Resources

Explore the Library

Find interesting tutorials and solutions for your problems.