1
1
import * as fs from "fs" ;
2
2
import path = require( "path" ) ;
3
3
import { promisify } from "util" ;
4
+ import Logging = require( "./Logging" ) ;
4
5
5
6
export const statAsync = promisify ( fs . stat ) ;
6
7
export const lstatAsync = promisify ( fs . lstat ) ;
@@ -39,15 +40,19 @@ export const confirmDirExists = async (directory: string): Promise<void> => {
39
40
* Computes the size (in bytes) of all files in a directory at the root level. Asynchronously.
40
41
*/
41
42
export const getShallowDirectorySize = async ( directory : string ) : Promise < number > => {
42
- // Get the directory listing
43
- const files = await readdirAsync ( directory ) ;
44
43
let totalSize = 0 ;
45
- // Query all file sizes
46
- for ( const file of files ) {
47
- const fileStats = await statAsync ( path . join ( directory , file ) ) ;
48
- if ( fileStats . isFile ( ) ) {
49
- totalSize += fileStats . size ;
44
+ try {
45
+ // Get the directory listing
46
+ const files = await readdirAsync ( directory ) ;
47
+ // Query all file sizes
48
+ for ( const file of files ) {
49
+ const fileStats = await statAsync ( path . join ( directory , file ) ) ;
50
+ if ( fileStats . isFile ( ) ) {
51
+ totalSize += fileStats . size ;
52
+ }
50
53
}
54
+ } catch {
55
+ Logging . warn ( `Failed to get directory size for ${ directory } ` ) ;
51
56
}
52
57
return totalSize ;
53
58
} ;
@@ -56,21 +61,30 @@ export const getShallowDirectorySize = async (directory: string): Promise<number
56
61
* Computes the size (in bytes) of all files in a directory at the root level. Synchronously.
57
62
*/
58
63
export const getShallowDirectorySizeSync = ( directory : string ) : number => {
59
- let files = fs . readdirSync ( directory ) ;
60
64
let totalSize = 0 ;
61
- for ( let i = 0 ; i < files . length ; i ++ ) {
62
- totalSize += fs . statSync ( path . join ( directory , files [ i ] ) ) . size ;
65
+ try {
66
+ let files = fs . readdirSync ( directory ) ;
67
+ for ( let i = 0 ; i < files . length ; i ++ ) {
68
+ totalSize += fs . statSync ( path . join ( directory , files [ i ] ) ) . size ;
69
+ }
70
+ } catch {
71
+ Logging . warn ( `Failed to get directory size synchronously for ${ directory } ` )
63
72
}
64
- return totalSize ;
73
+ return totalSize
65
74
}
66
75
67
76
/**
68
- * Computes the size (in bytes) of a file asynchronously.
77
+ * Computes the size (in bytes) of a file asynchronously. Returns -1 if the file does not exist.
69
78
*/
70
79
export const getShallowFileSize = async ( filePath : string ) : Promise < number > => {
71
- const fileStats = await statAsync ( filePath ) ;
72
- if ( fileStats . isFile ( ) ) {
73
- return fileStats . size ;
80
+ try {
81
+ const fileStats = await statAsync ( filePath ) ;
82
+ if ( fileStats . isFile ( ) ) {
83
+ return fileStats . size ;
84
+ }
85
+ } catch {
86
+ Logging . warn ( `Failed to get file size for ${ filePath } ` ) ;
87
+ return - 1 ;
74
88
}
75
89
}
76
90
0 commit comments