-
-
Notifications
You must be signed in to change notification settings - Fork 7
/
util.js
51 lines (39 loc) · 1.32 KB
/
util.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
// https://www.npmjs.com/package/get-folder-size
// Adapted for CommonJS and synchronous Filesystem calls.
const fs = require('fs')
const path = require('path')
async function getFolderSize (rootItemPath, options = {}) {
const fileSizes = new Map()
await processItem(rootItemPath)
async function processItem (itemPath) {
if (options.ignore?.test(itemPath)) return
const stats = lstatSync(itemPath, { bigint: true })
if (typeof stats !== 'object') return
fileSizes.set(stats.ino, stats.size)
if (stats.isDirectory()) {
const directoryItems = fs.readdirSync(itemPath)
if (typeof directoryItems !== 'object') return
await Promise.all(
directoryItems.map(directoryItem =>
processItem(path.join(itemPath, directoryItem))
)
)
}
}
let folderSize = Array.from(fileSizes.values()).reduce((total, fileSize) => total + fileSize, 0n)
if (!options.bigint) {
if (folderSize > BigInt(Number.MAX_SAFE_INTEGER)) {
throw new RangeError('The folder size is too large to return as a Number. You can instruct this package to return a BigInt instead.')
}
folderSize = Number(folderSize)
}
return folderSize
}
function lstatSync(path, opts) {
try {
return fs.lstatSync(path, opts)
} catch (error) {
return
}
}
module.exports = { getFolderSize }