-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfs.ts
More file actions
1955 lines (1871 loc) · 55 KB
/
fs.ts
File metadata and controls
1955 lines (1871 loc) · 55 KB
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @fileoverview File system utilities with cross-platform path handling.
* Provides enhanced fs operations, glob matching, and directory traversal functions.
*/
import process from 'node:process'
import { isArray } from './arrays'
import { getAbortSignal } from './constants/process'
import { defaultIgnore, getGlobMatcher } from './globs'
import { jsonParse } from './json/parse'
import { objectFreeze, type Remap } from './objects'
import { normalizePath, pathLikeToString } from './paths/normalize'
import { registerCacheInvalidation } from './paths/rewire'
import {
getOsTmpDir,
getSocketCacacheDir,
getSocketUserDir,
} from './paths/socket'
import { pRetry } from './promises'
import { naturalCompare } from './sorts'
import type { Abortable } from 'node:events'
import type {
Dirent,
MakeDirectoryOptions,
ObjectEncodingOptions,
OpenMode,
PathLike,
StatSyncOptions,
WriteFileOptions,
} from 'node:fs'
import type {
deleteAsync as deleteAsyncType,
deleteSync as deleteSyncType,
} from './external/del'
import type { JsonReviver } from './json/types'
const abortSignal = getAbortSignal()
// Module-level regex constants — avoid re-allocating on every call.
const NEWLINE_REGEX = /\n/g
/**
* Supported text encodings for Node.js Buffers.
* Includes ASCII, UTF-8/16, base64, binary, and hexadecimal encodings.
*/
export type BufferEncoding =
| 'ascii'
| 'utf8'
| 'utf-8'
| 'utf16le'
| 'ucs2'
| 'ucs-2'
| 'base64'
| 'base64url'
| 'latin1'
| 'binary'
| 'hex'
/**
* Options for asynchronous `findUp` operations.
*/
export interface FindUpOptions {
/**
* Starting directory for the search.
* @default process.cwd()
*/
cwd?: string | undefined
/**
* Only match directories, not files.
* @default false
*/
onlyDirectories?: boolean | undefined
/**
* Only match files, not directories.
* @default true
*/
onlyFiles?: boolean | undefined
/**
* Abort signal to cancel the search operation.
*/
signal?: AbortSignal | undefined
}
/**
* Options for synchronous `findUpSync` operations.
*/
export interface FindUpSyncOptions {
/**
* Starting directory for the search.
* @default process.cwd()
*/
cwd?: string | undefined
/**
* Directory to stop searching at (inclusive).
* When provided, search will stop at this directory even if the root hasn't been reached.
*/
stopAt?: string | undefined
/**
* Only match directories, not files.
* @default false
*/
onlyDirectories?: boolean | undefined
/**
* Only match files, not directories.
* @default true
*/
onlyFiles?: boolean | undefined
}
/**
* Options for checking if a directory is empty.
*/
export interface IsDirEmptyOptions {
/**
* Glob patterns for files to ignore when checking emptiness.
* Files matching these patterns are not counted.
* @default defaultIgnore
*/
ignore?: string[] | readonly string[] | undefined
}
/**
* Represents any valid JSON content type.
*/
export type JsonContent = unknown
/**
* Options for reading directories with filtering and sorting.
*/
export interface ReadDirOptions {
/**
* Glob patterns for directories to ignore.
* @default undefined
*/
ignore?: string[] | readonly string[] | undefined
/**
* Include empty directories in results.
* When `false`, empty directories are filtered out.
* @default true
*/
includeEmpty?: boolean | undefined
/**
* Sort directory names alphabetically using natural sort order.
* @default true
*/
sort?: boolean | undefined
}
/**
* Options for reading files with encoding and abort support.
* Can be either an options object, an encoding string, or null.
*/
export type ReadFileOptions =
| Remap<
ObjectEncodingOptions &
Abortable & {
flag?: OpenMode | undefined
}
>
| BufferEncoding
| null
/**
* Options for reading and parsing JSON files.
*/
export type ReadJsonOptions = Remap<
ReadFileOptions & {
/**
* Whether to throw errors on parse failure.
* When `false`, returns `undefined` on error instead of throwing.
* @default true
*/
throws?: boolean | undefined
/**
* JSON reviver function to transform parsed values.
* Same as the second parameter to `JSON.parse()`.
*/
reviver?: Parameters<typeof JSON.parse>[1] | undefined
}
>
/**
* Options for read operations with abort support.
*/
export interface ReadOptions extends Abortable {
/**
* Character encoding to use for reading.
* @default 'utf8'
*/
encoding?: BufferEncoding | string | undefined
/**
* File system flag for reading behavior.
* @default 'r'
*/
flag?: string | undefined
}
/**
* Options for file/directory removal operations.
*/
export interface RemoveOptions {
/**
* Force deletion even outside normally safe directories.
* When `false`, prevents deletion outside temp, cacache, and ~/.socket.
* @default true for safe directories, false otherwise
*/
force?: boolean | undefined
/**
* Maximum number of retry attempts on failure.
* @default 3
*/
maxRetries?: number | undefined
/**
* Recursively delete directories and contents.
* @default true
*/
recursive?: boolean | undefined
/**
* Delay in milliseconds between retry attempts.
* @default 200
*/
retryDelay?: number | undefined
/**
* Abort signal to cancel the operation.
*/
signal?: AbortSignal | undefined
}
/**
* Options for safe read operations that don't throw on errors.
*/
export interface SafeReadOptions extends ReadOptions {
/**
* Default value to return on read failure.
* If not provided, `undefined` is returned on error.
*/
defaultValue?: unknown | undefined
}
/**
* Result of file readability validation.
* Contains lists of valid and invalid file paths.
*/
export interface ValidateFilesResult {
/**
* File paths that passed validation and are readable.
*/
validPaths: string[]
/**
* File paths that failed validation (unreadable, permission denied, or non-existent).
* Common with Yarn Berry PnP virtual filesystem, pnpm symlinks, or filesystem race conditions.
*/
invalidPaths: string[]
}
/**
* Options for writing JSON files with formatting control.
*/
export interface WriteJsonOptions extends WriteOptions {
/**
* End-of-line sequence to use.
* @default '\n'
* @example
* ```ts
* // Windows-style line endings
* writeJson('data.json', data, { EOL: '\r\n' })
* ```
*/
EOL?: string | undefined
/**
* Whether to add a final newline at end of file.
* @default true
*/
finalEOL?: boolean | undefined
/**
* JSON replacer function to transform values during stringification.
* Same as the second parameter to `JSON.stringify()`.
*/
replacer?: JsonReviver | undefined
/**
* Number of spaces for indentation, or string to use for indentation.
* @default 2
* @example
* ```ts
* // Use tabs instead of spaces
* writeJson('data.json', data, { spaces: '\t' })
*
* // Use 4 spaces for indentation
* writeJson('data.json', data, { spaces: 4 })
* ```
*/
spaces?: number | string | undefined
}
/**
* Options for write operations with encoding and mode control.
*/
export interface WriteOptions extends Abortable {
/**
* Character encoding for writing.
* @default 'utf8'
*/
encoding?: BufferEncoding | string | undefined
/**
* File mode (permissions) to set.
* Uses standard Unix permission bits (e.g., 0o644).
* @default 0o666 (read/write for all, respecting umask)
*/
mode?: number | undefined
/**
* File system flag for write behavior.
* @default 'w' (create or truncate)
*/
flag?: string | undefined
}
const defaultRemoveOptions = objectFreeze({
__proto__: null,
force: true,
maxRetries: 3,
recursive: true,
retryDelay: 200,
})
let _del:
| { deleteAsync: typeof deleteAsyncType; deleteSync: typeof deleteSyncType }
| undefined
// Cache for resolved allowed directories
let _cachedAllowedDirs: string[] | undefined
let _buffer: typeof import('node:buffer') | undefined
let _fs: typeof import('node:fs') | undefined
let _path: typeof import('node:path') | undefined
/**
* Get resolved allowed directories for safe deletion with lazy caching.
* These directories are resolved once and cached for the process lifetime.
* @private
*/
function getAllowedDirectories(): string[] {
if (_cachedAllowedDirs === undefined) {
const path = getPath()
_cachedAllowedDirs = [
path.resolve(getOsTmpDir()),
path.resolve(getSocketCacacheDir()),
path.resolve(getSocketUserDir()),
]
}
return _cachedAllowedDirs
}
/**
* Lazily load the buffer module.
*
* Performs on-demand loading of Node.js buffer module to avoid initialization
* overhead and potential Webpack bundling errors.
*
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getBuffer() {
if (_buffer === undefined) {
// Use non-'node:' prefixed require to avoid Webpack errors.
_buffer = /*@__PURE__*/ require('node:buffer')
}
return _buffer as typeof import('node:buffer')
}
/*@__NO_SIDE_EFFECTS__*/
function getDel() {
if (_del === undefined) {
_del = /*@__PURE__*/ require('./external/del')
}
return _del!
}
/**
* Lazily load the fs module to avoid Webpack errors.
* Uses non-'node:' prefixed require to prevent Webpack bundling issues.
*
* @returns The Node.js fs module
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getFs() {
if (_fs === undefined) {
// Use non-'node:' prefixed require to avoid Webpack errors.
_fs = /*@__PURE__*/ require('node:fs')
}
return _fs as typeof import('node:fs')
}
/**
* Lazily load the path module to avoid Webpack errors.
* Uses non-'node:' prefixed require to prevent Webpack bundling issues.
*
* @returns The Node.js path module
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function getPath() {
if (_path === undefined) {
// Use non-'node:' prefixed require to avoid Webpack errors.
_path = /*@__PURE__*/ require('node:path')
}
return _path as typeof import('node:path')
}
/**
* Process directory entries and filter for directories.
* Filters entries to include only directories, optionally excluding empty ones.
* Applies ignore patterns and natural sorting.
*
* @param dirents - Directory entries from readdir
* @param dirname - Parent directory path
* @param options - Filtering and sorting options
* @returns Array of directory names, optionally sorted
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function innerReadDirNames(
dirents: Dirent[],
dirname: string | undefined,
options?: ReadDirOptions | undefined,
): string[] {
const {
ignore,
includeEmpty = true,
sort = true,
} = { __proto__: null, ...options } as ReadDirOptions
const path = getPath()
const names = dirents
.filter(
(d: Dirent) =>
d.isDirectory() &&
(includeEmpty ||
!isDirEmptySync(path.join(dirname || d.parentPath, d.name), {
ignore,
})),
)
.map((d: Dirent) => d.name)
return sort ? names.sort(naturalCompare) : names
}
/**
* Stringify JSON with custom formatting options.
* Formats JSON with configurable line endings and indentation.
*
* @param json - Value to stringify
* @param EOL - End-of-line sequence
* @param finalEOL - Whether to add final newline
* @param replacer - JSON replacer function
* @param spaces - Indentation spaces or string
* @returns Formatted JSON string
* @private
*/
/*@__NO_SIDE_EFFECTS__*/
function stringify(
json: unknown,
EOL: string,
finalEOL: boolean,
replacer: JsonReviver | undefined,
spaces: number | string = 2,
): string {
const EOF = finalEOL ? EOL : ''
const str = JSON.stringify(json, replacer, spaces)
return `${str.replace(NEWLINE_REGEX, EOL)}${EOF}`
}
/**
* Find a file or directory by traversing up parent directories.
* Searches from the starting directory upward to the filesystem root.
* Useful for finding configuration files or project roots.
*
* @param name - Filename(s) to search for
* @param options - Search options including cwd and type filters
* @returns Normalized absolute path if found, undefined otherwise
*
* @example
* ```ts
* // Find package.json starting from current directory
* const pkgPath = await findUp('package.json')
*
* // Find any of multiple config files
* const configPath = await findUp(['.config.js', '.config.json'])
*
* // Find a directory instead of file
* const nodeModules = await findUp('node_modules', { onlyDirectories: true })
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export async function findUp(
name: string | string[] | readonly string[],
options?: FindUpOptions | undefined,
): Promise<string | undefined> {
const { cwd = process.cwd(), signal = abortSignal } = {
__proto__: null,
...options,
} as FindUpOptions
let { onlyDirectories = false, onlyFiles = true } = {
__proto__: null,
...options,
} as FindUpOptions
if (onlyDirectories) {
onlyFiles = false
}
if (onlyFiles) {
onlyDirectories = false
}
const fs = getFs()
const path = getPath()
let dir = path.resolve(cwd)
const { root } = path.parse(dir)
const names = isArray(name) ? name : [name as string]
// Traverse up to and INCLUDING the filesystem root. Previously the
// loop exited when `dir === root`, so a match at e.g. `/.foo` was
// never visited.
while (dir) {
for (const n of names) {
if (signal?.aborted) {
return undefined
}
const thePath = path.join(dir, n)
try {
// eslint-disable-next-line no-await-in-loop
const stats = await fs.promises.stat(thePath)
if (!onlyDirectories && stats.isFile()) {
return normalizePath(thePath)
}
if (!onlyFiles && stats.isDirectory()) {
return normalizePath(thePath)
}
} catch {}
}
if (dir === root) {
break
}
dir = path.dirname(dir)
}
return undefined
}
/**
* Synchronously find a file or directory by traversing up parent directories.
* Searches from the starting directory upward to the filesystem root or `stopAt` directory.
* Useful for finding configuration files or project roots in synchronous contexts.
*
* @param name - Filename(s) to search for
* @param options - Search options including cwd, stopAt, and type filters
* @returns Normalized absolute path if found, undefined otherwise
*
* @example
* ```ts
* // Find package.json starting from current directory
* const pkgPath = findUpSync('package.json')
*
* // Find .git directory but stop at home directory
* const gitPath = findUpSync('.git', {
* onlyDirectories: true,
* stopAt: process.env.HOME
* })
*
* // Find any of multiple config files
* const configPath = findUpSync(['.eslintrc.js', '.eslintrc.json'])
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function findUpSync(
name: string | string[] | readonly string[],
options?: FindUpSyncOptions | undefined,
) {
const { cwd = process.cwd(), stopAt } = {
__proto__: null,
...options,
} as FindUpSyncOptions
let { onlyDirectories = false, onlyFiles = true } = {
__proto__: null,
...options,
} as FindUpSyncOptions
if (onlyDirectories) {
onlyFiles = false
}
if (onlyFiles) {
onlyDirectories = false
}
const fs = getFs()
const path = getPath()
let dir = path.resolve(cwd)
const { root } = path.parse(dir)
const stopDir = stopAt ? path.resolve(stopAt) : undefined
const names = isArray(name) ? name : [name as string]
// Traverse up to and INCLUDING the filesystem root (or stopAt). The
// old `while (dir && dir !== root)` exited before visiting `root`
// itself, so a match at `/.foo` was never found.
while (dir) {
// Check if we should stop at this directory.
if (stopDir && dir === stopDir) {
// Check current directory but don't go up.
for (const n of names) {
const thePath = path.join(dir, n)
try {
const stats = fs.statSync(thePath)
if (!onlyDirectories && stats.isFile()) {
return normalizePath(thePath)
}
if (!onlyFiles && stats.isDirectory()) {
return normalizePath(thePath)
}
} catch {}
}
return undefined
}
for (const n of names) {
const thePath = path.join(dir, n)
try {
const stats = fs.statSync(thePath)
if (!onlyDirectories && stats.isFile()) {
return normalizePath(thePath)
}
if (!onlyFiles && stats.isDirectory()) {
return normalizePath(thePath)
}
} catch {}
}
if (dir === root) {
break
}
dir = path.dirname(dir)
}
return undefined
}
/**
* Invalidate the cached allowed directories.
* Called automatically by the paths/rewire module when paths are overridden in tests.
*
* @internal Used for test rewiring
*
* @example
* ```typescript
* invalidatePathCache()
* // Cached allowed directories are now cleared
* ```
*/
export function invalidatePathCache(): void {
_cachedAllowedDirs = undefined
}
/**
* Check if a path is a directory asynchronously.
* Returns `true` for directories, `false` for files or non-existent paths.
*
* @param filepath - Path to check
* @returns `true` if path is a directory, `false` otherwise
*
* @example
* ```ts
* if (await isDir('./src')) {
* console.log('src is a directory')
* }
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export async function isDir(filepath: PathLike) {
return !!(await safeStats(filepath))?.isDirectory()
}
/**
* Check if a directory is empty synchronously.
* A directory is considered empty if it contains no files after applying ignore patterns.
* Uses glob patterns to filter ignored files.
*
* @param dirname - Directory path to check
* @param options - Options including ignore patterns
* @returns `true` if directory is empty (or doesn't exist), `false` otherwise
*
* @example
* ```ts
* // Check if directory is completely empty
* isDirEmptySync('./build')
*
* // Check if directory is empty, ignoring .DS_Store files
* isDirEmptySync('./cache', { ignore: ['.DS_Store'] })
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isDirEmptySync(
dirname: PathLike,
options?: IsDirEmptyOptions | undefined,
) {
const { ignore = defaultIgnore } = {
__proto__: null,
...options,
} as IsDirEmptyOptions
const fs = getFs()
try {
const files = fs.readdirSync(dirname)
const { length } = files
if (length === 0) {
return true
}
const matcher = getGlobMatcher(
ignore as string[],
{
cwd: pathLikeToString(dirname),
} as { cwd?: string; dot?: boolean; ignore?: string[]; nocase?: boolean },
)
let ignoredCount = 0
for (let i = 0; i < length; i += 1) {
const file = files[i]
if (file && matcher(file)) {
ignoredCount += 1
}
}
return ignoredCount === length
} catch {
// Return false for non-existent paths or other errors.
return false
}
}
/**
* Check if a path is a directory synchronously.
* Returns `true` for directories, `false` for files or non-existent paths.
*
* @param filepath - Path to check
* @returns `true` if path is a directory, `false` otherwise
*
* @example
* ```ts
* if (isDirSync('./src')) {
* console.log('src is a directory')
* }
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isDirSync(filepath: PathLike) {
return !!safeStatsSync(filepath)?.isDirectory()
}
/**
* Check if a path is a symbolic link synchronously.
* Uses `lstat` to check the link itself, not the target.
*
* @param filepath - Path to check
* @returns `true` if path is a symbolic link, `false` otherwise
*
* @example
* ```ts
* if (isSymLinkSync('./my-link')) {
* console.log('Path is a symbolic link')
* }
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function isSymLinkSync(filepath: PathLike) {
const fs = getFs()
try {
return fs.lstatSync(filepath).isSymbolicLink()
} catch {}
return false
}
/**
* Normalize encoding string to canonical form.
* Handles common encodings inline for performance, delegates to slowCases for others.
*
* Based on Node.js internal/util.js normalizeEncoding implementation.
* @see https://github.com/nodejs/node/blob/ae62b36d442b7bf987e85ae6e0df0f02cc1bb17f/lib/internal/util.js#L247-L310
*
* @param enc - Encoding to normalize (can be null/undefined)
* @returns Normalized encoding string, defaults to 'utf8'
*
* @example
* ```ts
* normalizeEncoding('UTF-8') // Returns 'utf8'
* normalizeEncoding('binary') // Returns 'latin1'
* normalizeEncoding('ucs-2') // Returns 'utf16le'
* normalizeEncoding(null) // Returns 'utf8'
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function normalizeEncoding(
enc: BufferEncoding | string | null | undefined,
): BufferEncoding {
return enc == null || enc === 'utf8' || enc === 'utf-8'
? 'utf8'
: normalizeEncodingSlow(enc)
}
/**
* Move the "slow cases" to a separate function to make sure this function gets
* inlined properly. That prioritizes the common case.
*
* Based on Node.js internal/util.js normalizeEncoding implementation.
* @see https://github.com/nodejs/node/blob/ae62b36d442b7bf987e85ae6e0df0f02cc1bb17f/lib/internal/util.js#L247-L310
*
* @param enc - Encoding to normalize
* @returns Normalized encoding string, defaults to 'utf8' for unknown encodings
*
* @example
* ```typescript
* normalizeEncodingSlow('ucs2') // 'utf16le'
* normalizeEncodingSlow('LATIN1') // 'latin1'
* normalizeEncodingSlow('binary') // 'latin1'
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function normalizeEncodingSlow(enc: string): BufferEncoding {
const { length } = enc
if (length === 4) {
if (enc === 'ucs2' || enc === 'UCS2') {
return 'utf16le'
}
if (enc.toLowerCase() === 'ucs2') {
return 'utf16le'
}
} else if (
(length === 3 && enc === 'hex') ||
enc === 'HEX' ||
enc.toLowerCase() === 'hex'
) {
return 'hex'
} else if (length === 5) {
if (enc === 'ascii') {
return 'ascii'
}
if (enc === 'ucs-2') {
return 'utf16le'
}
if (enc === 'ASCII') {
return 'ascii'
}
if (enc === 'UCS-2') {
return 'utf16le'
}
enc = enc.toLowerCase()
if (enc === 'ascii') {
return 'ascii'
}
if (enc === 'ucs-2') {
return 'utf16le'
}
} else if (length === 6) {
if (enc === 'base64') {
return 'base64'
}
if (enc === 'latin1' || enc === 'binary') {
return 'latin1'
}
if (enc === 'BASE64') {
return 'base64'
}
if (enc === 'LATIN1' || enc === 'BINARY') {
return 'latin1'
}
enc = enc.toLowerCase()
if (enc === 'base64') {
return 'base64'
}
if (enc === 'latin1' || enc === 'binary') {
return 'latin1'
}
} else if (length === 7) {
if (
enc === 'utf16le' ||
enc === 'UTF16LE' ||
enc.toLowerCase() === 'utf16le'
) {
return 'utf16le'
}
} else if (length === 8) {
if (
enc === 'utf-16le' ||
enc === 'UTF-16LE' ||
enc.toLowerCase() === 'utf-16le'
) {
return 'utf16le'
}
} else if (length === 9) {
if (
enc === 'base64url' ||
enc === 'BASE64URL' ||
enc.toLowerCase() === 'base64url'
) {
return 'base64url'
}
}
return 'utf8'
}
/**
* Read directory names asynchronously with filtering and sorting.
* Returns only directory names (not files), with optional filtering for empty directories
* and glob-based ignore patterns. Results are naturally sorted by default.
*
* @param dirname - Directory path to read
* @param options - Options for filtering and sorting
* @returns Array of directory names, empty array on error
*
* @example
* ```ts
* // Get all subdirectories, sorted naturally
* const dirs = await readDirNames('./packages')
*
* // Get non-empty directories only
* const nonEmpty = await readDirNames('./cache', { includeEmpty: false })
*
* // Get directories without sorting
* const unsorted = await readDirNames('./src', { sort: false })
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export async function readDirNames(
dirname: PathLike,
options?: ReadDirOptions | undefined,
) {
const fs = getFs()
try {
return innerReadDirNames(
await fs.promises.readdir(dirname, {
__proto__: null,
encoding: 'utf8',
withFileTypes: true,
} as ObjectEncodingOptions & { withFileTypes: true }),
String(dirname),
options,
)
} catch {}
return []
}
/**
* Read directory names synchronously with filtering and sorting.
* Returns only directory names (not files), with optional filtering for empty directories
* and glob-based ignore patterns. Results are naturally sorted by default.
*
* @param dirname - Directory path to read
* @param options - Options for filtering and sorting
* @returns Array of directory names, empty array on error
*
* @example
* ```ts
* // Get all subdirectories, sorted naturally
* const dirs = readDirNamesSync('./packages')
*
* // Get non-empty directories only, ignoring node_modules
* const nonEmpty = readDirNamesSync('./src', {
* includeEmpty: false,
* ignore: ['node_modules']
* })
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export function readDirNamesSync(dirname: PathLike, options?: ReadDirOptions) {
const fs = getFs()
try {
return innerReadDirNames(
fs.readdirSync(dirname, {
__proto__: null,
encoding: 'utf8',
withFileTypes: true,
} as ObjectEncodingOptions & { withFileTypes: true }),
String(dirname),
options,
)
} catch {}
return []
}
/**
* Read a file as binary data asynchronously.
* Returns a Buffer without encoding the contents.
* Useful for reading images, archives, or other binary formats.
*
* @param filepath - Path to file
* @param options - Read options (encoding is forced to null for binary)
* @returns Promise resolving to Buffer containing file contents
*
* @example
* ```ts
* // Read an image file
* const imageBuffer = await readFileBinary('./image.png')
*
* // Read with abort signal
* const buffer = await readFileBinary('./data.bin', { signal: abortSignal })
* ```
*/
/*@__NO_SIDE_EFFECTS__*/
export async function readFileBinary(
filepath: PathLike,
options?: ReadFileOptions | undefined,
) {
// Don't specify encoding to get a Buffer.
const opts = typeof options === 'string' ? { encoding: options } : options