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.
Synchronous version:
xxxxxxxxxx
1
const fs = require('fs');
2
3
const stats = fs.statSync('/path/to/file.txt');
4
const fileSizeInBytes = stats.size;
5
const fileSizeInMegabytes = fileSizeInBytes / (1024 * 1024); // file size in MB
6
7
console.log(fileSizeInBytes + ' bytes')
8
console.log(fileSizeInMegabytes + ' megabytes')
Asynchronous version:
xxxxxxxxxx
1
const fs = require('fs/promises');
2
3
const displaySize = async (path) => {
4
const stats = await fs.stat(path);
5
const fileSizeInBytes = stats.size;
6
console.log(fileSizeInBytes + ' bytes');
7
8
const fileSizeInMegabytes = fileSizeInBytes / (1024 * 1024); // file size in MB
9
console.log(fileSizeInMegabytes + ' megabytes');
10
};
11
12
displaySize('/path/to/file.txt');