Languages
[Edit]
EN

Node.js - get file size

0 points
Created by:
Joanne-Senior
530

In this article, we would like to show you how to get file size in Node.js.

Practical example

Synchronous version:

const fs = require('fs');

const stats = fs.statSync('/path/to/file.txt');
const fileSizeInBytes = stats.size;
const fileSizeInMegabytes = fileSizeInBytes / (1024 * 1024);  // file size in MB

console.log(fileSizeInBytes + ' bytes')
console.log(fileSizeInMegabytes + ' megabytes')

Asynchronous version:

const fs = require('fs/promises');

const displaySize = async (path) => {
    const stats = await fs.stat(path);
    const fileSizeInBytes = stats.size;
    console.log(fileSizeInBytes + ' bytes');

    const fileSizeInMegabytes = fileSizeInBytes / (1024 * 1024); // file size in MB
    console.log(fileSizeInMegabytes + ' megabytes');
};

displaySize('/path/to/file.txt');

Node.js - file system module

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join