-
Notifications
You must be signed in to change notification settings - Fork 7
/
fs.ts
1593 lines (1483 loc) · 46.6 KB
/
fs.ts
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
/**
* Universal file system APIs for both server and browser applications.
*
* This module is guaranteed to work in the following environments:
*
* - Node.js
* - Deno
* - Bun
* - Modern browsers
* - Cloudflare Workers (limited support and experimental)
*
* We can also use the {@link runtime} function to check whether the runtime
* has file system support. When `runtime().fsSupport` is `true`, this module
* should work properly.
*
* In most browsers, this module uses the
* [Origin Private File System](https://developer.mozilla.org/en-US/docs/Web/API/File_System_API/Origin_private_file_system).
* In Chromium browsers, this module can also access the device's local file
* system via `window.showOpenFilePicker()` and `window.showDirectoryPicker()`.
*
* This module also provides limited support for Cloudflare Workers, however it
* requires setting the `[site].bucket` option in the `wrangler.toml` file. Only
* the reading functions are supported, such as {@link readFile} and
* {@link readDir}, these functions allow us reading static files in the workers,
* writing functions is not implemented at the moment. More details about
* serving static assets in Cloudflare Workers can be found here:
* [Add static assets to an existing Workers project](https://developers.cloudflare.com/workers/configuration/sites/start-from-worker/).
*
* **Errors:**
*
* When a file system operation fails, this module throws an {@link Exception}
* with one of the following names:
*
* - `NotFoundError`: The file or directory does not exist.
* - `NotAllowedError`: The operation is not allowed, such as being blocked by
* the permission system.
* - `AlreadyExistsError`: The file or directory already exists.
* - `IsDirectoryError`: The path is a directory, not a file.
* - `NotDirectoryError`: The path is a file, not a directory.
* - `InvalidOperationError`: The operation is not supported, such as trying to
* copy a directory without the `recursive` option.
* - `BusyError`: The file is busy, such as being locked by another program.
* - `InterruptedError`: The operation is interrupted by the underlying file
* system.
* - `FileTooLargeError`: The file is too large, or the file system doesn't have
* enough space to store the new content.
* - `FilesystemLoopError`: Too many symbolic links were encountered when
* resolving the filename.
*
* Other errors may also be thrown by the runtime, such as `TypeError`.
* @module
*/
import bytes from "./bytes.ts";
import { isDeno, isNodeLike } from "./env.ts";
import { Exception } from "./error.ts";
import { getMIME } from "./filetype.ts";
import type { FileInfo, DirEntry, FileSystemOptions, DirTree } from "./fs/types.ts";
import { ensureFsTarget, fixDirEntry, makeTree, rawOp, wrapFsError } from "./fs/util.ts";
import { resolveHomeDir } from "./fs/util/server.ts";
import {
getDirHandle,
getFileHandle,
stat as webStat,
mkdir as webMakeDir,
readDir as webReadDir,
readFile as webReadFile,
readFileAsFile as webReadFileAsFile,
writeFile as webWriteFile,
truncate as webTruncate,
remove as webRemove,
rename as webRename,
copy as webCopy,
createReadableStream as webCreateReadableStream,
createWritableStream as webCreateWritableStream,
} from "./fs/web.ts";
import { as } from "./object.ts";
import { basename, extname, join } from "./path.ts";
import { readAsArray, readAsText, resolveByteStream } from "./reader.ts";
import runtime, { platform } from "./runtime.ts";
import _try from "./try.ts";
export type { FileSystemOptions, FileInfo, DirEntry, DirTree };
export { getDirHandle, getFileHandle };
/**
* Platform-specific end-of-line marker. The value is `\r\n` in Windows
* server-side environments, and `\n` elsewhere.
*/
export const EOL: "\n" | "\r\n" = (() => {
if (typeof Deno === "object" && typeof Deno.build === "object") {
return Deno.build.os === "windows" ? "\r\n" : "\n";
} else if (typeof process === "object" && typeof process.platform === "string") {
return process.platform === "win32" ? "\r\n" : "\n";
} else {
return "\n";
}
})();
/**
* Options for the {@link getDirHandle} function.
*/
export interface GetDirOptions extends FileSystemOptions {
/**
* Create the directory if not exist.
*/
create?: boolean;
/**
* Used when `create` is `true`, recursively create the directory and its
* parent directories.
*/
recursive?: boolean;
}
/**
* Options for the {@link getFileHandle} function.
*/
export interface GetFileOptions extends FileSystemOptions {
/**
* Create the file if not exist.
*/
create?: boolean;
}
/**
* Checks if the given path exists.
*
* This function may throw an error if the path is invalid or the operation is
* not allowed.
*
* NOTE: This function can also be used in Cloudflare Workers.
*
* @example
* ```ts
* // with the default storage
* import { exists } from "@ayonli/jsext/fs";
*
* if (await exists("/path/to/file.txt")) {
* console.log("The file exists.");
* } else {
* console.log("The file does not exist.");
* }
* ```
*
* @example
* ```ts
* // with a user-selected directory as root (Chromium only)
* import { exists } from "@ayonli/jsext/fs";
*
* const root = await window.showDirectoryPicker();
*
* if (await exists("/path/to/file.txt", { root })) {
* console.log("The file exists.");
* } else {
* console.log("The file does not exist.");
* }
* ```
*/
export async function exists(path: string | URL, options: FileSystemOptions = {}): Promise<boolean> {
try {
await stat(path, options);
return true;
} catch (err) {
if (err instanceof Exception) {
if (err.name === "NotFoundError") {
return false;
}
}
throw err;
}
}
/**
* Options for the {@link stat} function.
*/
export interface StatOptions extends FileSystemOptions {
/**
* Whether to follow the symbolic link.
* @default false
*/
followSymlink?: boolean;
}
/**
* Returns the information of the given file or directory.
*
* NOTE: This function can also be used in Cloudflare Workers.
*
* @example
* ```ts
* // with the default storage
* import { stat } from "@ayonli/jsext/fs";
*
* const info = await stat("/path/to/file.txt");
* console.log(`${info.name} is a ${info.kind}, its size is ${info.size} bytes, with MIME type ${info.type}.`);
* ```
*
* @example
* ```ts
* // with a user-selected directory as root (Chromium only)
* import { stat } from "@ayonli/jsext/fs";
*
* const root = await window.showDirectoryPicker();
* const info = await stat("/path/to/file.txt", { root });
* console.log(`${info.name} is a ${info.kind}, its size is ${info.size} bytes, with MIME type ${info.type}.`);
* ```
*/
export async function stat(
target: string | URL | FileSystemFileHandle | FileSystemDirectoryHandle,
options: StatOptions = {}
): Promise<FileInfo> {
target = ensureFsTarget(target);
if (typeof target === "object" || !(isDeno || isNodeLike)) {
return await webStat(target, options);
}
const path = await resolveHomeDir(target);
if (isDeno) {
const stat = await rawOp(options.followSymlink ? Deno.stat(path) : Deno.lstat(path));
const kind = stat.isDirectory
? "directory"
: stat.isSymlink
? "symlink"
: "file";
return {
name: basename(path),
kind,
size: stat.size,
type: kind === "file" ? (getMIME(extname(path)) ?? "") : "",
mtime: stat.mtime ?? null,
atime: stat.atime ?? null,
birthtime: stat.birthtime ?? null,
mode: stat.mode ?? 0,
uid: stat.uid ?? 0,
gid: stat.gid ?? 0,
isBlockDevice: stat.isBlockDevice ?? false,
isCharDevice: stat.isCharDevice ?? false,
isFIFO: stat.isFifo ?? false,
isSocket: stat.isSocket ?? false,
};
} else {
const fs = await import("node:fs/promises");
const stat = await rawOp(options.followSymlink ? fs.stat(path) : fs.lstat(path));
const kind = stat.isDirectory()
? "directory"
: stat.isSymbolicLink()
? "symlink"
: "file";
return {
name: basename(path),
kind,
size: stat.size,
type: kind === "file" ? (getMIME(extname(path)) ?? "") : "",
mtime: stat.mtime ?? null,
atime: stat.atime ?? null,
birthtime: stat.birthtime ?? null,
mode: stat.mode ?? 0,
uid: stat.uid ?? 0,
gid: stat.gid ?? 0,
isBlockDevice: stat.isBlockDevice(),
isCharDevice: stat.isCharacterDevice(),
isFIFO: stat.isFIFO(),
isSocket: stat.isSocket(),
};
}
}
/**
* Options for the {@link mkdir} function.
*/
export interface MkdirOptions extends FileSystemOptions {
/**
* Whether to create parent directories if they do not exist.
*/
recursive?: boolean;
/**
* The permission mode of the directory.
*
* NOTE: This option is ignored in the browser and in Windows.
* @default 0o777
*/
mode?: number;
}
/**
* Creates a new directory with the given path.
*
* @example
* ```ts
* // with the default storage
* import { mkdir } from "@ayonli/jsext/fs";
*
* await mkdir("/path/to/dir");
* ```
*
* @example
* ```ts
* // with a user-selected directory as root (Chromium only)
* import { mkdir } from "@ayonli/jsext/fs";
*
* const root = await window.showDirectoryPicker();
* await mkdir("/path/to/dir", { root });
* ```
*
* @example
* ```ts
* // create the directory and its parent directories if not exist
* import { mkdir } from "@ayonli/jsext/fs";
*
* await mkdir("/path/to/dir", { recursive: true });
* ```
*/
export async function mkdir(path: string | URL, options: MkdirOptions = {}): Promise<void> {
path = ensureFsTarget(path);
if (!(isDeno || isNodeLike)) {
return await webMakeDir(path, options);
}
path = await resolveHomeDir(path);
if (isDeno) {
await rawOp(Deno.mkdir(path, options));
} else {
const fs = await import("node:fs/promises");
await rawOp(fs.mkdir(path, options));
}
}
/**
* Ensures the directory exists, creating it (and any parent directory) if not.
*
* @example
* ```ts
* // with the default storage
* import { ensureDir } from "@ayonli/jsext/fs";
*
* await ensureDir("/path/to/dir");
* ```
*
* @example
* ```ts
* // with a user-selected directory as root (Chromium only)
* import { ensureDir } from "@ayonli/jsext/fs";
*
* const root = await window.showDirectoryPicker();
* await ensureDir("/path/to/dir", { root });
* ```
*/
export async function ensureDir(
path: string | URL,
options: Omit<MkdirOptions, "recursive"> = {}
): Promise<void> {
if (await exists(path, options)) {
return;
}
try {
await mkdir(path, { ...options, recursive: true });
} catch (err) {
if (as(err, Exception)?.name === "AlreadyExistsError") {
return;
} else {
throw err;
}
}
}
/**
* Options for the {@link readDir} function.
*/
export interface ReadDirOptions extends FileSystemOptions {
/**
* Whether to read the sub-directories recursively.
*/
recursive?: boolean;
}
/**
* Reads the directory of the given path and iterates its entries.
*
* NOTE: The order of the entries is not guaranteed.
*
* NOTE: This function can also be used in Cloudflare Workers.
*
* @example
* ```ts
* // with the default storage
* import { readDir } from "@ayonli/jsext/fs";
*
* for await (const entry of readDir("/path/to/dir")) {
* console.log(`${entry.name} is a ${entry.kind}, its relative path is '${entry.relativePath}'.`);
* }
* ```
*
* @example
* ```ts
* // with a user-selected directory as root (Chromium only)
* import { readDir } from "@ayonli/jsext/fs";
*
* const root = await window.showDirectoryPicker();
* for await (const entry of readDir("/path/to/dir", { root })) {
* console.log(`${entry.name} is a ${entry.kind}, its relative path is '${entry.relativePath}'.`);
* }
* ```
*
* @example
* ```ts
* // read the sub-directories recursively
* import { readDir } from "@ayonli/jsext/fs";
*
* for await (const entry of readDir("/path/to/dir", { recursive: true })) {
* console.log(`${entry.name} is a ${entry.kind}, its relative path is '${entry.relativePath}'.`);
* }
* ```
*/
export async function* readDir(
target: string | URL | FileSystemDirectoryHandle,
options: ReadDirOptions = {}
): AsyncIterableIterator<DirEntry> {
target = ensureFsTarget(target);
if (typeof target === "object" || !(isDeno || isNodeLike)) {
yield* webReadDir(target, options);
return;
}
const path = await resolveHomeDir(target);
if (isDeno) {
yield* (async function* read(path: string, base: string): AsyncIterableIterator<DirEntry> {
try {
for await (const entry of Deno.readDir(path)) {
const _entry = fixDirEntry({
name: entry.name,
kind: entry.isDirectory
? "directory"
: entry.isSymlink
? "symlink"
: "file",
relativePath: join(base, entry.name),
});
yield _entry;
if (options?.recursive && entry.isDirectory) {
yield* read(join(path, entry.name), _entry.relativePath);
}
}
} catch (err) {
throw wrapFsError(err);
}
})(path, "");
} else {
const fs = await import("node:fs/promises");
yield* (async function* read(path: string, base: string): AsyncIterableIterator<DirEntry> {
const entries = await rawOp(fs.readdir(path, { withFileTypes: true }));
for (const entry of entries) {
const _entry = fixDirEntry({
name: entry.name,
kind: entry.isDirectory()
? "directory"
: entry.isSymbolicLink()
? "symlink"
: "file",
relativePath: join(base, entry.name),
});
yield _entry;
if (options?.recursive && entry.isDirectory()) {
yield* read(join(path, entry.name), _entry.relativePath);
}
}
})(path, "");
}
}
/**
* Recursively reads the contents of the directory and transform them into a
* tree structure.
*
* NOTE: Unlike {@link readDir}, the order of the entries returned by this
* function is guaranteed, they are ordered first by kind (directories before
* files), then by names alphabetically.
*
* NOTE: This function can also be used in Cloudflare Workers.
*
* @example
* ```ts
* // with the default storage
* import { readTree } from "@ayonli/jsext/fs";
*
* const tree = await readTree("/path/to/dir");
* console.log(tree);
* ```
*
* @example
* ```ts
* // with a user-selected directory as root (Chromium only)
* import { readTree } from "@ayonli/jsext/fs";
*
* const root = await window.showDirectoryPicker();
* const tree = await readTree("/path/to/dir", { root });
* console.log(tree);
* ```
*/
export async function readTree(
target: string | URL | FileSystemDirectoryHandle,
options: FileSystemOptions = {}
): Promise<DirTree> {
target = ensureFsTarget(target);
const entries = (await readAsArray(readDir(target, { ...options, recursive: true })));
const tree = makeTree<DirEntry, DirTree>(target, entries, true);
if (!tree.handle && options.root) {
tree.handle = options.root as FileSystemDirectoryHandle;
}
return tree;
}
/**
* Options for file reading functions, such as {@link readFile},
* {@link readFileAsText} and {@link readFileAsFile}.
*/
export interface ReadFileOptions extends FileSystemOptions {
signal?: AbortSignal;
}
/**
* Reads the content of the given file in bytes.
*
* NOTE: This function can also be used in Cloudflare Workers.
*
* @example
* ```ts
* // with the default storage
* import { readFile } from "@ayonli/jsext/fs";
*
* const bytes = await readFile("/path/to/file.txt");
* ```
*
* @example
* ```ts
* // with a user-selected directory as root (Chromium only)
* import { readFile } from "@ayonli/jsext/fs";
*
* const root = await window.showDirectoryPicker();
* const bytes = await readFile("/path/to/file.txt", { root });
* ```
*/
export async function readFile(
target: string | URL | FileSystemFileHandle,
options: ReadFileOptions = {}
): Promise<Uint8Array> {
target = ensureFsTarget(target);
if (typeof target === "object" || !(isDeno || isNodeLike)) {
return await webReadFile(target, options);
}
const filename = await resolveHomeDir(target);
if (isDeno) {
return await rawOp(Deno.readFile(filename, options));
} else {
const fs = await import("node:fs/promises");
const buffer = await rawOp(fs.readFile(filename, options));
return new Uint8Array(buffer.buffer, buffer.byteOffset, buffer.byteLength);
}
}
/**
* Reads the content of the given file as text.
*
* NOTE: This function can also be used in Cloudflare Workers.
*
* @example
* ```ts
* // with the default storage
* import { readFileAsText } from "@ayonli/jsext/fs";
*
* const text = await readFileAsText("/path/to/file.txt");
* ```
*
* @example
* ```ts
* // with a user-selected directory as root (Chromium only)
* import { readFileAsText } from "@ayonli/jsext/fs";
*
* const root = await window.showDirectoryPicker();
* const text = await readFileAsText("/path/to/file.txt", { root });
* ```
*
* @example
* ```ts
* // with a specific encoding
* import { readFileAsText } from "@ayonli/jsext/fs";
*
* const text = await readFileAsText("./examples/samples/gb2312.txt", { encoding: "gb2312" });
* ```
*/
export async function readFileAsText(
target: string | URL | FileSystemFileHandle,
options: ReadFileOptions & { encoding?: string; } = {}
): Promise<string> {
const { encoding, ...rest } = options;
const file = await readFile(target, rest);
return await readAsText(file, encoding);
}
/**
* Reads the file as a `File` object.
*
* NOTE: This function can also be used in Cloudflare Workers.
*
* @example
* ```ts
* // with the default storage
* import { readFileAsFile } from "@ayonli/jsext/fs";
*
* const file = await readFileAsFile("/path/to/file.txt");
* ```
*
* @example
* ```ts
* // with a user-selected directory as root (Chromium only)
* import { readFileAsFile } from "@ayonli/jsext/fs";
*
* const root = await window.showDirectoryPicker();
* const file = await readFileAsFile("/path/to/file.txt", { root });
* ```
*/
export async function readFileAsFile(
target: string | URL | FileSystemFileHandle,
options: ReadFileOptions = {}
): Promise<File> {
target = ensureFsTarget(target);
if (typeof target === "object" || !(isDeno || isNodeLike)) {
return await webReadFileAsFile(target, options);
}
const bytes = await readFile(target, options);
const type = getMIME(extname(target)) ?? "";
const file = new File([bytes], basename(target), { type });
Object.defineProperty(file, "webkitRelativePath", {
configurable: true,
enumerable: true,
writable: false,
value: "",
});
return file;
}
/**
* Options for file writing functions, such as {@link writeFile} and {@link writeLines}.
*/
export interface WriteFileOptions extends FileSystemOptions {
/**
* Append the data to the file instead of overwriting it.
*/
append?: boolean;
/**
* Permissions always applied to file.
*
* NOTE: This option is ignored in the browser.
* @default 0o666
*/
mode?: number;
signal?: AbortSignal;
}
/**
* Writes the given data to the file.
*
* @example
* ```ts
* // with the default storage
* import { writeFile } from "@ayonli/jsext/fs";
*
* await writeFile("/path/to/file.txt", "Hello, world!");
* ```
*
* @example
* ```ts
* // with a user-selected directory as root (Chromium only)
* import { writeFile } from "@ayonli/jsext/fs";
*
* const root = await window.showDirectoryPicker();
* await writeFile("/path/to/file.txt", "Hello, world!", { root });
* ```
*
* @example
* ```ts
* // append the data to the file
* import { writeFile } from "@ayonli/jsext/fs";
*
* await writeFile("/path/to/file.txt", "Hello, world!", { append: true });
* ```
*
* @example
* ```ts
* // write binary data to the file
* import { writeFile } from "@ayonli/jsext/fs";
* import bytes from "@ayonli/jsext/bytes";
*
* const data = bytes("Hello, world!");
* await writeFile("/path/to/file.txt", data)
* ```
*
* @example
* ```ts
* // write a blob to the file
* import { writeFile } from "@ayonli/jsext/fs";
*
* const blob = new Blob(["Hello, world!"], { type: "text/plain" });
* await writeFile("/path/to/file.txt", blob);
* ```
*
* @example
* ```ts
* // write a readable stream to the file
* import { writeFile } from "@ayonli/jsext/fs";
*
* const res = await fetch("https://example.com/file.txt");
* await writeFile("/path/to/file.txt", res.body!);
* ```
*/
export async function writeFile(
target: string | URL | FileSystemFileHandle,
data: string | ArrayBuffer | ArrayBufferView | ReadableStream<Uint8Array> | Blob,
options: WriteFileOptions = {}
): Promise<void> {
target = ensureFsTarget(target);
if (typeof target === "object" || !(isDeno || isNodeLike)) {
return await webWriteFile(target, data, options);
}
const filename = await resolveHomeDir(target);
if (isDeno) {
if (typeof data === "string") {
return await rawOp(Deno.writeTextFile(filename, data, options));
} else if (data instanceof Blob) {
return await rawOp(Deno.writeFile(filename, data.stream(), options));
} else if (data instanceof ArrayBuffer) {
return await rawOp(Deno.writeFile(filename, new Uint8Array(data), options));
} else if (data instanceof Uint8Array) {
return await rawOp(Deno.writeFile(filename, data, options));
} else if (ArrayBuffer.isView(data)) {
return await rawOp(Deno.writeFile(filename, bytes(data), options));
} else if (data) {
return await rawOp(Deno.writeFile(filename, data, options));
}
} else {
if (typeof Blob === "function" && data instanceof Blob) {
const reader = data.stream();
const writer = createNodeWritableStream(filename, options);
await reader.pipeTo(writer);
} else if (typeof ReadableStream === "function" && data instanceof ReadableStream) {
const writer = createNodeWritableStream(filename, options);
await data.pipeTo(writer);
} else {
const fs = await import("node:fs/promises");
const { append, ...rest } = options;
let _data: Uint8Array | string;
if (data instanceof ArrayBuffer) {
_data = new Uint8Array(data);
} else if (data instanceof Uint8Array) {
_data = data;
} else if (ArrayBuffer.isView(data)) {
_data = bytes(data);
} else if (typeof data === "string") {
_data = data;
} else {
throw new TypeError("Unsupported data type");
}
return await rawOp(fs.writeFile(filename, _data, {
flag: append ? "a" : "w",
...rest,
}));
}
}
}
/**
* Writes multiple lines of content to the file.
*
* This function will automatically detect the line ending of the current
* content and use it to write the new lines. If the file is empty or does not
* exists (will be created automatically), it will use the system's default line
* ending to separate lines.
*
* This function will append a new line at the end of the final content, in
* appending mode, it will also prepend a line ending before the input lines if
* the current content doesn't ends with one.
*
* @example
* ```ts
* // with the default storage
* import { writeLines } from "@ayonli/jsext/fs";
*
* await writeLines("/path/to/file.txt", ["Hello", "World"]);
* ```
*
* @example
* ```ts
* // with a user-selected directory as root (Chromium only)
* import { writeLines } from "@ayonli/jsext/fs";
*
* const root = await window.showDirectoryPicker();
* await writeLines("/path/to/file.txt", ["Hello", "World"], { root });
* ```
*
* @example
* ```ts
* // append the lines to the file
* import { writeLines } from "@ayonli/jsext/fs";
*
* await writeLines("/path/to/file.txt", ["Hello", "World"], { append: true });
* ```
*/
export async function writeLines(
target: string | URL | FileSystemFileHandle,
lines: string[],
options: WriteFileOptions = {}
): Promise<void> {
const current = await readFileAsText(target, options).catch(err => {
if (as(err, Exception)?.name !== "NotFoundError") {
throw err;
} else {
return "";
}
});
const lineEndings = current.match(/\r?\n/g);
let eol = EOL;
if (lineEndings) {
const crlf = lineEndings.filter(e => e === "\r\n").length;
const lf = lineEndings.length - crlf;
eol = crlf > lf ? "\r\n" : "\n";
}
let content = lines.join(eol);
if (!content.endsWith(eol)) {
if (eol === "\r\n" && content.endsWith("\r")) {
content += "\n";
} else {
content += eol;
}
}
if (options.append && !current.endsWith(eol) && !content.startsWith(eol)) {
if (eol === "\r\n" && current.endsWith("\r")) {
if (!content.startsWith("\n")) {
content = "\n" + content;
}
} else {
content = eol + content;
}
}
await writeFile(target, content, options);
}
/**
* Truncates (or extends) the file to reach the specified `size`. If `size` is
* not specified then the entire file contents are truncated.
*
* @example
* ```ts
* // with the default storage
* import { stat, truncate } from "@ayonli/jsext/fs";
*
* await truncate("/path/to/file.txt", 1024);
* const info = await stat("/path/to/file.txt");
* console.assert(info.size === 1024);
* ```
*
* @example
* ```ts
* // with a user-selected directory as root (Chromium only)
* import { stat, truncate } from "@ayonli/jsext/fs";
*
* const root = await window.showDirectoryPicker();
* await truncate("/path/to/file.txt", 1024, { root });
* const info = await stat("/path/to/file.txt", { root });
* console.assert(info.size === 1024);
* ```
*
* @example
* ```ts
* // truncate the file to zero size
* import { stat, truncate } from "@ayonli/jsext/fs";
*
* await truncate("/path/to/file.txt");
* const info = await stat("/path/to/file.txt");
* console.assert(info.size === 0);
* ```
*/
export async function truncate(
target: string | URL | FileSystemFileHandle,
size = 0,
options: FileSystemOptions = {}
): Promise<void> {
target = ensureFsTarget(target);
if (typeof target === "object" || !(isDeno || isNodeLike)) {
return await webTruncate(target, size, options);
}
const filename = await resolveHomeDir(target);
if (isDeno) {
await rawOp(Deno.truncate(filename, size));
} else {
const fs = await import("node:fs/promises");
await rawOp(fs.truncate(filename, size));
}
}
/**
* Options for the {@link remove} function.
*/
export interface RemoveOptions extends FileSystemOptions {
/**
* Whether to delete the sub-directories and files recursively. This option
* is required in order to remove a non-empty directory.
*/
recursive?: boolean;
}
/**
* Removes the file or directory of the given path from the file system.
*
* @example
* ```ts
* // with the default storage
* import { remove } from "@ayonli/jsext/fs";
*
* await remove("/path/to/file.txt");
* ```
*
* @example
* ```ts
* // with a user-selected directory as root (Chromium only)
* import { remove } from "@ayonli/jsext/fs";
*
* const root = await window.showDirectoryPicker();
* await remove("/path/to/file.txt", { root });
* ```
*
* @example
* ```ts
* // remove the directory and its contents recursively
* import { remove } from "@ayonli/jsext/fs";
*
* await remove("/path/to/dir", { recursive: true });
* ```
*/
export async function remove(path: string | URL, options: RemoveOptions = {}): Promise<void> {
path = ensureFsTarget(path);
if (!(isDeno || isNodeLike)) {
return await webRemove(path, options);
}
path = await resolveHomeDir(path);
if (isDeno) {
await rawOp(Deno.remove(path, options));
} else {
const fs = await import("node:fs/promises");
if (typeof fs.rm === "function") {
await rawOp(fs.rm(path, options));
} else {
try {
const _stat = await fs.stat(path);
if (_stat.isDirectory()) {
await fs.rmdir(path, options);
} else {
await fs.unlink(path);