-
Notifications
You must be signed in to change notification settings - Fork 2.8k
/
fs.test.ts
3498 lines (3083 loc) · 108 KB
/
fs.test.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
import { describe, expect, it, spyOn } from "bun:test";
import { bunEnv, bunExe, gc, getMaxFD, isIntelMacOS, isWindows, tempDirWithFiles, tmpdirSync } from "harness";
import { isAscii } from "node:buffer";
import fs, {
closeSync,
constants,
copyFileSync,
createReadStream,
createWriteStream,
Dir,
Dirent,
existsSync,
fdatasync,
fdatasyncSync,
fstatSync,
lstatSync,
mkdirSync,
mkdtemp,
mkdtempSync,
openAsBlob,
openSync,
promises,
readdirSync,
readFile,
readFileSync,
readlinkSync,
readSync,
readvSync,
realpathSync,
renameSync,
rmdir,
rmdirSync,
rmSync,
Stats,
statSync,
symlinkSync,
unlinkSync,
writeFileSync,
writeSync,
writevSync,
} from "node:fs";
import { dirname, relative, resolve } from "node:path";
import { promisify } from "node:util";
import _promises, { type FileHandle } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { spawnSync } from "bun";
import { ReadStream as ReadStream_, WriteStream as WriteStream_ } from "./export-from.js";
import { ReadStream as ReadStreamStar_, WriteStream as WriteStreamStar_ } from "./export-star-from.js";
const Buffer = globalThis.Buffer || Uint8Array;
if (!import.meta.dir) {
//@ts-expect-error
import.meta.dir = ".";
}
function mkdirForce(path: string) {
if (!existsSync(path)) mkdirSync(path, { recursive: true });
}
function tmpdirTestMkdir(): string {
const now = Date.now().toString();
const tempdir = `${tmpdir()}/fs.test.ts/${now}/1234/hi`;
expect(existsSync(tempdir)).toBe(false);
const res = mkdirSync(tempdir, { recursive: true });
if (!res?.includes(now)) {
expect(res).toInclude("fs.test.ts");
}
expect(res).not.toInclude("1234");
expect(existsSync(tempdir)).toBe(true);
return tempdir;
}
it("fs.writeFile(1, data) should work when its inherited", async () => {
expect([join(import.meta.dir, "fs-writeFile-1-fixture.js"), "1"]).toRun();
});
it("fs.writeFile(2, data) should work when its inherited", async () => {
expect([join(import.meta.dir, "fs-writeFile-1-fixture.js"), "2"]).toRun();
});
it("fs.writeFile(/dev/null, data) should work", async () => {
expect([join(import.meta.dir, "fs-writeFile-1-fixture.js"), require("os").devNull]).toRun();
});
it("fs.openAsBlob", async () => {
expect((await openAsBlob(import.meta.path)).size).toBe(statSync(import.meta.path).size);
});
it("writing to 1, 2 are possible", () => {
expect(fs.writeSync(1, Buffer.from("\nhello-stdout-test\n"))).toBe(19);
expect(fs.writeSync(2, Buffer.from("\nhello-stderr-test\n"))).toBe(19);
});
describe("test-fs-assert-encoding-error", () => {
const testPath = join(tmpdirSync(), "assert-encoding-error");
const options = "test";
const expectedError = expect.objectContaining({
code: "ERR_INVALID_ARG_VALUE",
name: "TypeError",
});
it("readFile throws on invalid encoding", () => {
expect(() => {
fs.readFile(testPath, options, () => {});
}).toThrow(expectedError);
});
it("readFileSync throws on invalid encoding", () => {
expect(() => {
fs.readFileSync(testPath, options);
}).toThrow(expectedError);
});
it("readdir throws on invalid encoding", () => {
expect(() => {
fs.readdir(testPath, options, () => {});
}).toThrow(expectedError);
});
it("readdirSync throws on invalid encoding", () => {
expect(() => {
fs.readdirSync(testPath, options);
}).toThrow(expectedError);
});
it("readlink throws on invalid encoding", () => {
expect(() => {
fs.readlink(testPath, options, () => {});
}).toThrow(expectedError);
});
it("readlinkSync throws on invalid encoding", () => {
expect(() => {
fs.readlinkSync(testPath, options);
}).toThrow(expectedError);
});
it("writeFile throws on invalid encoding", () => {
expect(() => {
fs.writeFile(testPath, "data", options, () => {});
}).toThrow(expectedError);
});
it("writeFileSync throws on invalid encoding", () => {
expect(() => {
fs.writeFileSync(testPath, "data", options);
}).toThrow(expectedError);
});
it("appendFile throws on invalid encoding", () => {
expect(() => {
fs.appendFile(testPath, "data", options, () => {});
}).toThrow(expectedError);
});
it("appendFileSync throws on invalid encoding", () => {
expect(() => {
fs.appendFileSync(testPath, "data", options);
}).toThrow(expectedError);
});
it("watch throws on invalid encoding", () => {
expect(() => {
fs.watch(testPath, options, () => {});
}).toThrow(expectedError);
});
it("realpath throws on invalid encoding", () => {
expect(() => {
fs.realpath(testPath, options, () => {});
}).toThrow(expectedError);
});
it("realpathSync throws on invalid encoding", () => {
expect(() => {
fs.realpathSync(testPath, options);
}).toThrow(expectedError);
});
it("mkdtemp throws on invalid encoding", () => {
expect(() => {
fs.mkdtemp(testPath, options, () => {});
}).toThrow(expectedError);
});
it("mkdtempSync throws on invalid encoding", () => {
expect(() => {
fs.mkdtempSync(testPath, options);
}).toThrow(expectedError);
});
it.todo("ReadStream throws on invalid encoding", () => {
expect(() => {
fs.ReadStream(testPath, options);
}).toThrow(expectedError);
});
it.todo("WriteStream throws on invalid encoding", () => {
expect(() => {
fs.WriteStream(testPath, options);
}).toThrow(expectedError);
});
});
// TODO: port node.js tests for these
it("fs.readv returns object", async done => {
const fd = await promisify(fs.open)(import.meta.path, "r");
const buffers = [Buffer.alloc(10), Buffer.alloc(10)];
fs.readv(fd, buffers, 0, (err, bytesRead, output) => {
promisify(fs.close)(fd);
if (err) {
done(err);
return;
}
expect(bytesRead).toBe(20);
expect(output).toEqual(buffers);
done();
});
});
it("fs.writev returns object", async done => {
const outpath = tempDirWithFiles("fswritevtest", { "a.txt": "b" });
const fd = await promisify(fs.open)(join(outpath, "b.txt"), "w");
const buffers = [Buffer.alloc(10), Buffer.alloc(10)];
fs.writev(fd, buffers, 0, (err, bytesWritten, output) => {
promisify(fs.close)(fd);
if (err) {
done(err);
return;
}
expect(bytesWritten).toBe(20);
expect(output).toEqual(buffers);
done();
});
});
describe("FileHandle", () => {
it("FileHandle#read returns object", async () => {
await using fd = await fs.promises.open(__filename);
const buf = Buffer.alloc(10);
expect(await fd.read(buf, 0, 10, 0)).toEqual({ bytesRead: 10, buffer: buf });
});
it("FileHandle#readv returns object", async () => {
await using fd = await fs.promises.open(__filename);
const buffers = [Buffer.alloc(10), Buffer.alloc(10)];
expect(await fd.readv(buffers, 0)).toEqual({ bytesRead: 20, buffers });
});
it("FileHandle#write throws EBADF when closed", async () => {
let handle: FileHandle;
let spy;
{
await using fd = await fs.promises.open(__filename);
handle = fd;
spy = spyOn(handle, "close");
const buffers = [Buffer.alloc(10), Buffer.alloc(10)];
expect(await fd.readv(buffers, 0)).toEqual({ bytesRead: 20, buffers });
}
expect(handle.close).toHaveBeenCalled();
expect(async () => await handle.read(Buffer.alloc(10))).toThrow("Bad file descriptor");
});
it("FileHandle#write returns object", async () => {
await using fd = await fs.promises.open(`${tmpdir()}/${Date.now()}.writeFile.txt`, "w");
const buf = Buffer.from("test");
expect(await fd.write(buf, 0, 4, 0)).toEqual({ bytesWritten: 4, buffer: buf });
});
it("FileHandle#writev returns object", async () => {
await using fd = await fs.promises.open(`${tmpdir()}/${Date.now()}.writeFile.txt`, "w");
const buffers = [Buffer.from("test"), Buffer.from("test")];
expect(await fd.writev(buffers, 0)).toEqual({ bytesWritten: 8, buffers });
});
it("FileHandle#readFile returns buffer", async () => {
await using fd = await fs.promises.open(__filename);
const buf = await fd.readFile();
expect(buf instanceof Buffer).toBe(true);
});
it("FileHandle#readableWebStream", async () => {
await using fd = await fs.promises.open(__filename);
const stream = fd.readableWebStream();
const reader = stream.getReader();
const chunk = await reader.read();
expect(chunk.value instanceof Uint8Array).toBe(true);
reader.releaseLock();
});
it("FileHandle#createReadStream", async () => {
await using fd = await fs.promises.open(__filename);
const readable = fd.createReadStream();
const data = await new Promise(resolve => {
let data = "";
readable.on("data", chunk => {
data += chunk;
});
readable.on("end", () => {
resolve(data);
});
});
expect(data).toBe(readFileSync(__filename, "utf8"));
});
it("FileHandle#writeFile", async () => {
const path = `${tmpdir()}/${Date.now()}.writeFile.txt`;
await using fd = await fs.promises.open(path, "w");
await fd.writeFile("File written successfully");
expect(readFileSync(path, "utf8")).toBe("File written successfully");
});
it("FileHandle#createWriteStream", async () => {
const path = `${tmpdir()}/${Date.now()}.createWriteStream.txt`;
{
await using fd = await fs.promises.open(path, "w");
const stream = fd.createWriteStream();
await new Promise((resolve, reject) => {
stream.on("error", e => {
reject(e);
});
stream.on("finish", () => {
resolve(true);
});
stream.write("Test file written successfully");
stream.end();
});
}
expect(readFileSync(path, "utf8")).toBe("Test file written successfully");
});
it("FileHandle#createWriteStream fixture 2", async () => {
const path = `${tmpdir()}/${Date.now()}.createWriteStream.txt`;
{
await using fd = await fs.promises.open(path, "w");
const stream = fd.createWriteStream();
await new Promise((resolve, reject) => {
stream.on("error", e => {
reject(e);
});
stream.on("close", () => {
resolve(true);
});
stream.write("Test file written successfully");
stream.end();
});
}
expect(readFileSync(path, "utf8")).toBe("Test file written successfully");
});
});
it("fdatasyncSync", () => {
const temp = tmpdir();
const fd = openSync(join(temp, "test.blob"), "w", 0o664);
fdatasyncSync(fd);
closeSync(fd);
});
it("fdatasync", done => {
const temp = tmpdir();
const fd = openSync(join(temp, "test.blob"), "w", 0o664);
fdatasync(fd, function () {
done(...arguments);
closeSync(fd);
});
});
it("Dirent.name setter", () => {
const dirent = Object.create(Dirent.prototype);
expect(dirent.name).toBeUndefined();
dirent.name = "hello";
expect(dirent.name).toBe("hello");
});
it("writeFileSync should correctly resolve ../..", () => {
const base = tmpdirSync();
const path = join(base, "foo", "bar");
mkdirSync(path, { recursive: true });
const cwd = process.cwd();
process.chdir(path);
writeFileSync("../../test.txt", "hello");
expect(readFileSync(join(base, "test.txt"), "utf8")).toBe("hello");
process.chdir(cwd);
});
it("writeFileSync in append should not truncate the file", () => {
const path = join(tmpdirSync(), "should-not-append.txt");
var str = "";
writeFileSync(path, "---BEGIN---");
str += "---BEGIN---";
for (let i = 0; i < 10; i++) {
const line = "Line #" + i;
str += line;
writeFileSync(path, line, { flag: "a" });
}
expect(readFileSync(path, "utf8")).toBe(str);
});
it("await readdir #3931", async () => {
const { exitCode } = spawnSync({
cmd: [bunExe(), join(import.meta.dir, "./repro-3931.js")],
env: bunEnv,
cwd: import.meta.dir,
});
expect(exitCode).toBe(0);
});
it("writeFileSync NOT in append SHOULD truncate the file", () => {
const path = join(tmpdirSync(), "should-not-append.txt");
for (let options of [{ flag: "w" }, { flag: undefined }, {}, undefined]) {
writeFileSync(path, "---BEGIN---", options);
var str = "---BEGIN---";
expect(readFileSync(path, "utf8")).toBe(str);
for (let i = 0; i < 10; i++) {
const line = "Line #" + i;
str = line;
writeFileSync(path, line, options);
expect(readFileSync(path, "utf8")).toBe(str);
}
}
});
describe("copyFileSync", () => {
it("should work for files < 128 KB", () => {
const tempdir = tmpdirTestMkdir();
// that don't exist
copyFileSync(import.meta.path, tempdir + "/copyFileSync.js");
expect(existsSync(tempdir + "/copyFileSync.js")).toBe(true);
expect(readFileSync(tempdir + "/copyFileSync.js", "utf-8")).toBe(readFileSync(import.meta.path, "utf-8"));
// that do exist
copyFileSync(tempdir + "/copyFileSync.js", tempdir + "/copyFileSync.js1");
writeFileSync(tempdir + "/copyFileSync.js1", "hello");
copyFileSync(tempdir + "/copyFileSync.js1", tempdir + "/copyFileSync.js");
expect(readFileSync(tempdir + "/copyFileSync.js", "utf-8")).toBe("hello");
});
it("should work for files > 128 KB ", () => {
const tempdir = tmpdirTestMkdir();
var buffer = new Int32Array(128 * 1024);
for (let i = 0; i < buffer.length; i++) {
buffer[i] = i % 256;
}
const hash = Bun.hash(buffer.buffer);
writeFileSync(tempdir + "/copyFileSync.src.blob", buffer.buffer);
expect(existsSync(tempdir + "/copyFileSync.dest.blob")).toBe(false);
expect(existsSync(tempdir + "/copyFileSync.src.blob")).toBe(true);
copyFileSync(tempdir + "/copyFileSync.src.blob", tempdir + "/copyFileSync.dest.blob");
expect(Bun.hash(readFileSync(tempdir + "/copyFileSync.dest.blob"))).toBe(hash);
buffer[0] = 255;
writeFileSync(tempdir + "/copyFileSync.src.blob", buffer.buffer);
copyFileSync(tempdir + "/copyFileSync.src.blob", tempdir + "/copyFileSync.dest.blob");
expect(Bun.hash(readFileSync(tempdir + "/copyFileSync.dest.blob"))).toBe(Bun.hash(buffer.buffer));
});
it("constants are right", () => {
expect(fs.constants.COPYFILE_EXCL).toBe(1);
expect(fs.constants.COPYFILE_FICLONE).toBe(2);
expect(fs.constants.COPYFILE_FICLONE_FORCE).toBe(4);
});
it("FICLONE option does not error ever", () => {
const tempdir = tmpdirTestMkdir();
// that don't exist
copyFileSync(import.meta.path, tempdir + "/copyFileSync.js", fs.constants.COPYFILE_FICLONE);
copyFileSync(import.meta.path, tempdir + "/copyFileSync.js", fs.constants.COPYFILE_FICLONE);
copyFileSync(import.meta.path, tempdir + "/copyFileSync.js", fs.constants.COPYFILE_FICLONE);
});
it("COPYFILE_EXCL works", () => {
const tempdir = tmpdirTestMkdir();
// that don't exist
copyFileSync(import.meta.path, tempdir + "/copyFileSync.js", fs.constants.COPYFILE_EXCL);
expect(() => {
copyFileSync(import.meta.path, tempdir + "/copyFileSync.js", fs.constants.COPYFILE_EXCL);
}).toThrow();
});
if (process.platform === "linux") {
describe("should work when copyFileRange is not available", () => {
it("on large files", () => {
const tempdir = tmpdirTestMkdir();
var buffer = new Int32Array(128 * 1024);
for (let i = 0; i < buffer.length; i++) {
buffer[i] = i % 256;
}
const hash = Bun.hash(buffer.buffer);
const src = tempdir + "/copyFileSync.src.blob";
const dest = tempdir + "/copyFileSync.dest.blob";
writeFileSync(src, buffer.buffer);
try {
expect(existsSync(dest)).toBe(false);
const { exitCode } = spawnSync({
stdio: ["inherit", "inherit", "inherit"],
cmd: [bunExe(), join(import.meta.dir, "./fs-fixture-copyFile-no-copy_file_range.js"), src, dest],
env: {
...bunEnv,
BUN_CONFIG_DISABLE_COPY_FILE_RANGE: "1",
},
});
expect(exitCode).toBe(0);
expect(Bun.hash(readFileSync(dest))).toBe(hash);
} finally {
rmSync(src, { force: true });
rmSync(dest, { force: true });
}
});
it("on small files", () => {
const tempdir = tmpdirTestMkdir();
var buffer = new Int32Array(1 * 1024);
for (let i = 0; i < buffer.length; i++) {
buffer[i] = i % 256;
}
const hash = Bun.hash(buffer.buffer);
const src = tempdir + "/copyFileSync.src.blob";
const dest = tempdir + "/copyFileSync.dest.blob";
try {
writeFileSync(src, buffer.buffer);
expect(existsSync(dest)).toBe(false);
const { exitCode } = spawnSync({
stdio: ["inherit", "inherit", "inherit"],
cmd: [bunExe(), join(import.meta.dir, "./fs-fixture-copyFile-no-copy_file_range.js"), src, dest],
env: {
...bunEnv,
BUN_CONFIG_DISABLE_COPY_FILE_RANGE: "1",
},
});
expect(exitCode).toBe(0);
expect(Bun.hash(readFileSync(dest))).toBe(hash);
} finally {
rmSync(src, { force: true });
rmSync(dest, { force: true });
}
});
});
}
});
describe("mkdirSync", () => {
it("should create a directory", () => {
const now = Date.now().toString();
const base = join(now, ".mkdirSync", "1234", "hi");
const tempdir = `${tmpdir()}/${base}`;
expect(existsSync(tempdir)).toBe(false);
const res = mkdirSync(tempdir, { recursive: true });
expect(res).toInclude(now);
expect(res).not.toInclude(".mkdirSync");
expect(existsSync(tempdir)).toBe(true);
});
it("should throw ENOENT for empty string", () => {
expect(() => mkdirSync("", { recursive: true })).toThrow("No such file or directory");
expect(() => mkdirSync("")).toThrow("No such file or directory");
});
it("throws for invalid options", () => {
const path = `${tmpdir()}/${Date.now()}.rm.dir2/foo/bar`;
expect(() =>
mkdirSync(
path,
// @ts-expect-error
{ recursive: "lalala" },
),
).toThrow('The "recursive" property must be of type boolean, got string');
});
});
it("readdirSync on import.meta.dir", () => {
const dirs = readdirSync(import.meta.dir);
expect(dirs.length > 0).toBe(true);
var match = false;
gc(true);
for (let i = 0; i < dirs.length; i++) {
if (dirs[i] === import.meta.file) {
match = true;
}
}
gc(true);
expect(match).toBe(true);
});
it("Dirent has the expected fields", () => {
const dir = tmpdirSync();
writeFileSync(join(dir, "file.txt"), "");
const dirs = readdirSync(dir, { withFileTypes: true });
expect(dirs.length).toBe(1);
expect(dirs[0].name).toBe("file.txt");
expect(dirs[0].path).toBe(dir);
expect(dirs[0].parentPath).toBe(dir);
});
it("promises.readdir on a large folder", async () => {
const huge = tmpdirSync();
for (let i = 0; i < 128; i++) {
writeFileSync(join(huge, "file-" + i), "");
}
for (let j = 0; j < 4; j++) {
const promises = await Promise.all([
fs.promises.readdir(huge),
fs.promises.readdir(huge),
fs.promises.readdir(huge),
fs.promises.readdir(huge),
]);
for (let chunk of promises) {
expect(chunk).toHaveLength(128);
chunk.sort();
let count = 0;
for (let i = 0; i < 128; i++) {
const current = chunk[i];
if (!current.startsWith("file-")) {
throw new Error("invalid file name");
}
const num = parseInt(current.slice(5));
// @ts-expect-error
count += !!(num >= 0 && num < 128);
}
expect(count).toBe(128);
}
}
rmSync(huge, { force: true, recursive: true });
});
it("promises.readFile", async () => {
expect(await fs.promises.readFile(import.meta.path, "utf-8")).toEqual(readFileSync(import.meta.path, "utf-8"));
expect(await fs.promises.readFile(import.meta.path, { encoding: "latin1" })).toEqual(
readFileSync(import.meta.path, { encoding: "latin1" }),
);
// We do this 20 times to check for any GC issues.
for (let i = 0; i < 20; i++) {
try {
await fs.promises.readFile("/i-dont-exist", "utf-8");
expect.unreachable();
} catch (e: any) {
expect(e).toBeInstanceOf(Error);
expect(e.message).toBe("No such file or directory");
expect(e.code).toBe("ENOENT");
expect(e.errno).toBe(-2);
expect(e.path).toBe("/i-dont-exist");
}
}
});
describe("promises.readFile", async () => {
const nodeOutput = [
{
"encoding": "utf8",
"text": "ascii",
"correct": {
"type": "Buffer",
"data": [97, 115, 99, 105, 105],
},
"out": "ascii",
},
{
"encoding": "utf8",
"text": "utf16 🍇 🍈 🍉 🍊 🍋",
"correct": {
"type": "Buffer",
"data": [
117, 116, 102, 49, 54, 32, 240, 159, 141, 135, 32, 240, 159, 141, 136, 32, 240, 159, 141, 137, 32, 240, 159,
141, 138, 32, 240, 159, 141, 139,
],
},
"out": "utf16 🍇 🍈 🍉 🍊 🍋",
},
{
"encoding": "utf8",
"text": "👍",
"correct": {
"type": "Buffer",
"data": [240, 159, 145, 141],
},
"out": "👍",
},
{
"encoding": "utf-8",
"text": "ascii",
"correct": {
"type": "Buffer",
"data": [97, 115, 99, 105, 105],
},
"out": "ascii",
},
{
"encoding": "utf-8",
"text": "utf16 🍇 🍈 🍉 🍊 🍋",
"correct": {
"type": "Buffer",
"data": [
117, 116, 102, 49, 54, 32, 240, 159, 141, 135, 32, 240, 159, 141, 136, 32, 240, 159, 141, 137, 32, 240, 159,
141, 138, 32, 240, 159, 141, 139,
],
},
"out": "utf16 🍇 🍈 🍉 🍊 🍋",
},
{
"encoding": "utf-8",
"text": "👍",
"correct": {
"type": "Buffer",
"data": [240, 159, 145, 141],
},
"out": "👍",
},
{
"encoding": "utf16le",
"text": "ascii",
"correct": {
"type": "Buffer",
"data": [97, 0, 115, 0, 99, 0, 105, 0, 105, 0],
},
"out": "ascii",
},
{
"encoding": "utf16le",
"text": "utf16 🍇 🍈 🍉 🍊 🍋",
"correct": {
"type": "Buffer",
"data": [
117, 0, 116, 0, 102, 0, 49, 0, 54, 0, 32, 0, 60, 216, 71, 223, 32, 0, 60, 216, 72, 223, 32, 0, 60, 216, 73,
223, 32, 0, 60, 216, 74, 223, 32, 0, 60, 216, 75, 223,
],
},
"out": "utf16 🍇 🍈 🍉 🍊 🍋",
},
{
"encoding": "utf16le",
"text": "👍",
"correct": {
"type": "Buffer",
"data": [61, 216, 77, 220],
},
"out": "👍",
},
{
"encoding": "latin1",
"text": "ascii",
"correct": {
"type": "Buffer",
"data": [97, 115, 99, 105, 105],
},
"out": "ascii",
},
{
"encoding": "latin1",
"text": "utf16 🍇 🍈 🍉 🍊 🍋",
"correct": {
"type": "Buffer",
"data": [117, 116, 102, 49, 54, 32, 60, 71, 32, 60, 72, 32, 60, 73, 32, 60, 74, 32, 60, 75],
},
"out": "utf16 <G <H <I <J <K",
},
{
"encoding": "latin1",
"text": "👍",
"correct": {
"type": "Buffer",
"data": [61, 77],
},
"out": "=M",
},
{
"encoding": "binary",
"text": "ascii",
"correct": {
"type": "Buffer",
"data": [97, 115, 99, 105, 105],
},
"out": "ascii",
},
{
"encoding": "binary",
"text": "utf16 🍇 🍈 🍉 🍊 🍋",
"correct": {
"type": "Buffer",
"data": [117, 116, 102, 49, 54, 32, 60, 71, 32, 60, 72, 32, 60, 73, 32, 60, 74, 32, 60, 75],
},
"out": "utf16 <G <H <I <J <K",
},
{
"encoding": "binary",
"text": "👍",
"correct": {
"type": "Buffer",
"data": [61, 77],
},
"out": "=M",
},
{
"encoding": "base64",
"text": "ascii",
"correct": {
"type": "Buffer",
"data": [106, 199, 34],
},
"out": "asci",
},
{
"encoding": "hex",
"text": "ascii",
"correct": {
"type": "Buffer",
"data": [],
},
"out": "",
},
{
"encoding": "hex",
"text": "utf16 🍇 🍈 🍉 🍊 🍋",
"correct": {
"type": "Buffer",
"data": [],
},
"out": "",
},
{
"encoding": "hex",
"text": "👍",
"correct": {
"type": "Buffer",
"data": [],
},
"out": "",
},
];
it("& fs.promises.writefile encodes & decodes", async () => {
const results = [];
for (let encoding of [
"utf8",
"utf-8",
"utf16le",
"latin1",
"binary",
"base64",
/* TODO: "base64url", */ "hex",
] as const) {
for (let text of ["ascii", "utf16 🍇 🍈 🍉 🍊 🍋", "👍"]) {
if (encoding === "base64" && !isAscii(Buffer.from(text)))
// TODO: output does not match Node.js, and it's not a problem with readFile specifically.
continue;
const correct = Buffer.from(text, encoding);
const outfile = join(
tmpdir(),
"promises.readFile-" + Date.now() + "-" + Math.random().toString(32) + "-" + encoding + ".txt",
);
writeFileSync(outfile, correct);
const out = await fs.promises.readFile(outfile, encoding);
{
const { promise, resolve, reject } = Promise.withResolvers();
fs.readFile(outfile, encoding, (err, data) => {
if (err) reject(err);
else resolve(data);
});
expect(await promise).toEqual(out);
}
expect(fs.readFileSync(outfile, encoding)).toEqual(out);
await promises.rm(outfile, { force: true });
expect(await promises.writeFile(outfile, text, encoding)).toBeUndefined();
expect(await promises.readFile(outfile, encoding)).toEqual(out);
promises.rm(outfile, { force: true });
results.push({
encoding,
text,
correct,
out,
});
}
}
expect(JSON.parse(JSON.stringify(results, null, 2))).toEqual(nodeOutput);
});
});
it("promises.readFile - UTF16 file path", async () => {
const filename = `superduperduperdupduperdupersuperduperduperduperduperduperdupersuperduperduperduperduperduperdupersuperduperduperdupe-Bun-👍-${Date.now()}-${
(Math.random() * 1024000) | 0
}.txt`;
const dest = join(tmpdir(), filename);
await fs.promises.copyFile(import.meta.path, dest);
const expected = readFileSync(import.meta.path, "utf-8");
Bun.gc(true);
for (let i = 0; i < 100; i++) {
expect(await fs.promises.readFile(dest, "utf-8")).toEqual(expected);
}
Bun.gc(true);
});
it("promises.readFile - atomized file path", async () => {
const filename = `superduperduperdupduperdupersuperduperduperduperduperduperdupersuperduperduperduperduperduperdupersuperduperduperdupe-Bun-👍-${Date.now()}-${
(Math.random() * 1024000) | 0
}.txt`;
const destInput = join(tmpdir(), filename);
// Force it to become an atomized string by making it a property access
const dest: string = (
{
[destInput]: destInput,
boop: 123,
} as const
)[destInput] as string;
await fs.promises.copyFile(import.meta.path, dest);
const expected = readFileSync(import.meta.path, "utf-8");
Bun.gc(true);
for (let i = 0; i < 100; i++) {
expect(await fs.promises.readFile(dest, "utf-8")).toEqual(expected);
}
Bun.gc(true);
});
it("promises.readFile with buffer as file path", async () => {
for (let i = 0; i < 10; i++)
expect(await fs.promises.readFile(Buffer.from(import.meta.path), "utf-8")).toEqual(
readFileSync(import.meta.path, "utf-8"),
);
});
it("promises.readdir on a large folder withFileTypes", async () => {
const huge = tmpdirSync();
let withFileTypes = { withFileTypes: true } as const;
for (let i = 0; i < 128; i++) {
writeFileSync(join(huge, "file-" + i), "");
}
for (let j = 0; j < 4; j++) {
const promises = await Promise.all([
fs.promises.readdir(huge, withFileTypes),
fs.promises.readdir(huge, withFileTypes),
fs.promises.readdir(huge, withFileTypes),
fs.promises.readdir(huge, withFileTypes),
]);
for (let chunk of promises) {
expect(chunk).toHaveLength(128);
chunk.sort();
let count = 0;
for (let i = 0; i < 128; i++) {
const current = chunk[i].name;
if (!current.startsWith("file-")) {
throw new Error("invalid file name");
}
const num = parseInt(current.slice(5));
// @ts-expect-error
count += !!(num >= 0 && num < 128);
}
expect(count).toBe(128);
}
}
rmSync(huge, { force: true, recursive: true });
});
it("statSync throwIfNoEntry", () => {
const path = join(tmpdirSync(), "does", "not", "exist");