EN
Node.js - get file size
0
points
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');