-
-
Notifications
You must be signed in to change notification settings - Fork 133
/
Copy pathvolume.ts
2766 lines (2290 loc) · 87.1 KB
/
volume.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 * as pathModule from 'path';
import { Node, Link, File } from './node';
import Stats from './Stats';
import Dirent from './Dirent';
import { Buffer, bufferAllocUnsafe, bufferFrom } from './internal/buffer';
import setImmediate from './setImmediate';
import queueMicrotask from './queueMicrotask';
import process from './process';
import setTimeoutUnref, { TSetTimeout } from './setTimeoutUnref';
import { Readable, Writable } from 'stream';
import { constants } from './constants';
import { EventEmitter } from 'events';
import { TEncodingExtended, TDataOut, strToEncoding, ENCODING_UTF8 } from './encoding';
import { FileHandle } from './node/FileHandle';
import * as util from 'util';
import * as misc from './node/types/misc';
import * as opts from './node/types/options';
import { FsCallbackApi, WritevCallback } from './node/types/FsCallbackApi';
import { FsPromises } from './node/FsPromises';
import { ToTreeOptions, toTreeSync } from './print';
import { ERRSTR, FLAGS, MODE } from './node/constants';
import {
getDefaultOpts,
getDefaultOptsAndCb,
getMkdirOptions,
getOptions,
getReadFileOptions,
getReaddirOptions,
getReaddirOptsAndCb,
getRmOptsAndCb,
getRmdirOptions,
optsAndCbGenerator,
getAppendFileOptsAndCb,
getAppendFileOpts,
getStatOptsAndCb,
getStatOptions,
getRealpathOptsAndCb,
getRealpathOptions,
getWriteFileOptions,
writeFileDefaults,
getOpendirOptsAndCb,
getOpendirOptions,
} from './node/options';
import {
validateCallback,
modeToNumber,
pathToFilename,
nullCheck,
createError,
genRndStr6,
flagsToNumber,
validateFd,
isFd,
isWin,
dataToBuffer,
getWriteArgs,
bufferToEncoding,
getWriteSyncArgs,
unixify,
} from './node/util';
import type { PathLike, symlink } from './node/types/misc';
import type { FsPromisesApi, FsSynchronousApi } from './node/types';
import { Dir } from './Dir';
const resolveCrossPlatform = pathModule.resolve;
const {
O_RDONLY,
O_WRONLY,
O_RDWR,
O_CREAT,
O_EXCL,
O_TRUNC,
O_APPEND,
O_DIRECTORY,
O_SYMLINK,
F_OK,
COPYFILE_EXCL,
COPYFILE_FICLONE_FORCE,
} = constants;
const { sep, relative, join, dirname } = pathModule.posix ? pathModule.posix : pathModule;
// ---------------------------------------- Types
// Node-style errors with a `code` property.
export interface IError extends Error {
code?: string;
}
export type TFileId = PathLike | number; // Number is used as a file descriptor.
export type TData = TDataOut | ArrayBufferView | DataView; // Data formats users can give us.
export type TFlags = string | number;
export type TMode = string | number; // Mode can be a String, although docs say it should be a Number.
export type TTime = number | string | Date;
export type TCallback<TData> = (error?: IError | null, data?: TData) => void;
// ---------------------------------------- Constants
const kMinPoolSpace = 128;
// ---------------------------------------- Error messages
const EPERM = 'EPERM';
const ENOENT = 'ENOENT';
const EBADF = 'EBADF';
const EINVAL = 'EINVAL';
const EEXIST = 'EEXIST';
const ENOTDIR = 'ENOTDIR';
const EMFILE = 'EMFILE';
const EACCES = 'EACCES';
const EISDIR = 'EISDIR';
const ENOTEMPTY = 'ENOTEMPTY';
const ENOSYS = 'ENOSYS';
const ERR_FS_EISDIR = 'ERR_FS_EISDIR';
const ERR_OUT_OF_RANGE = 'ERR_OUT_OF_RANGE';
// ---------------------------------------- Flags
export type TFlagsCopy =
| typeof constants.COPYFILE_EXCL
| typeof constants.COPYFILE_FICLONE
| typeof constants.COPYFILE_FICLONE_FORCE;
// ---------------------------------------- Options
// Options for `fs.appendFile` and `fs.appendFileSync`
export interface IAppendFileOptions extends opts.IFileOptions {}
// Options for `fs.watchFile`
export interface IWatchFileOptions {
persistent?: boolean;
interval?: number;
}
// Options for `fs.watch`
export interface IWatchOptions extends opts.IOptions {
persistent?: boolean;
recursive?: boolean;
}
// ---------------------------------------- Utility functions
type TResolve = (filename: string, base?: string) => string;
let resolve: TResolve = (filename, base = process.cwd()) => resolveCrossPlatform(base, filename);
if (isWin) {
const _resolve = resolve;
resolve = (filename, base) => unixify(_resolve(filename, base));
}
export function filenameToSteps(filename: string, base?: string): string[] {
const fullPath = resolve(filename, base);
const fullPathSansSlash = fullPath.substring(1);
if (!fullPathSansSlash) return [];
return fullPathSansSlash.split(sep);
}
export function pathToSteps(path: PathLike): string[] {
return filenameToSteps(pathToFilename(path));
}
export function dataToStr(data: TData, encoding: string = ENCODING_UTF8): string {
if (Buffer.isBuffer(data)) return data.toString(encoding);
else if (data instanceof Uint8Array) return bufferFrom(data).toString(encoding);
else return String(data);
}
// converts Date or number to a fractional UNIX timestamp
export function toUnixTimestamp(time) {
// tslint:disable-next-line triple-equals
if (typeof time === 'string' && +time == (time as any)) {
return +time;
}
if (time instanceof Date) {
return time.getTime() / 1000;
}
if (isFinite(time)) {
if (time < 0) {
return Date.now() / 1000;
}
return time;
}
throw new Error('Cannot parse time: ' + time);
}
function validateUid(uid: number) {
if (typeof uid !== 'number') throw TypeError(ERRSTR.UID);
}
function validateGid(gid: number) {
if (typeof gid !== 'number') throw TypeError(ERRSTR.GID);
}
// ---------------------------------------- Volume
type DirectoryContent = string | Buffer | null;
export interface DirectoryJSON<T extends DirectoryContent = DirectoryContent> {
[key: string]: T;
}
export interface NestedDirectoryJSON<T extends DirectoryContent = DirectoryContent> {
[key: string]: T | NestedDirectoryJSON;
}
function flattenJSON(nestedJSON: NestedDirectoryJSON): DirectoryJSON {
const flatJSON: DirectoryJSON = {};
function flatten(pathPrefix: string, node: NestedDirectoryJSON) {
for (const path in node) {
const contentOrNode = node[path];
const joinedPath = join(pathPrefix, path);
if (typeof contentOrNode === 'string' || contentOrNode instanceof Buffer) {
flatJSON[joinedPath] = contentOrNode;
} else if (typeof contentOrNode === 'object' && contentOrNode !== null && Object.keys(contentOrNode).length > 0) {
// empty directories need an explicit entry and therefore get handled in `else`, non-empty ones are implicitly considered
flatten(joinedPath, contentOrNode);
} else {
// without this branch null, empty-object or non-object entries would not be handled in the same way
// by both fromJSON() and fromNestedJSON()
flatJSON[joinedPath] = null;
}
}
}
flatten('', nestedJSON);
return flatJSON;
}
const notImplemented: (...args: any[]) => any = () => {
throw new Error('Not implemented');
};
/**
* `Volume` represents a file system.
*/
export class Volume implements FsCallbackApi, FsSynchronousApi {
static fromJSON(json: DirectoryJSON, cwd?: string): Volume {
const vol = new Volume();
vol.fromJSON(json, cwd);
return vol;
}
static fromNestedJSON(json: NestedDirectoryJSON, cwd?: string): Volume {
const vol = new Volume();
vol.fromNestedJSON(json, cwd);
return vol;
}
/**
* Global file descriptor counter. UNIX file descriptors start from 0 and go sequentially
* up, so here, in order not to conflict with them, we choose some big number and descrease
* the file descriptor of every new opened file.
* @type {number}
* @todo This should not be static, right?
*/
static fd: number = 0x7fffffff;
// Constructor function used to create new nodes.
// NodeClass: new (...args) => TNode = Node as new (...args) => TNode;
// Hard link to the root of this volume.
// root: Node = new (this.NodeClass)(null, '', true);
root: Link;
// I-node number counter.
ino: number = 0;
// A mapping for i-node numbers to i-nodes (`Node`);
inodes: { [ino: number]: Node } = {};
// List of released i-node numbers, for reuse.
releasedInos: number[] = [];
// A mapping for file descriptors to `File`s.
fds: { [fd: number]: File } = {};
// A list of reusable (opened and closed) file descriptors, that should be
// used first before creating a new file descriptor.
releasedFds: number[] = [];
// Max number of open files.
maxFiles = 10000;
// Current number of open files.
openFiles = 0;
StatWatcher: new () => StatWatcher;
ReadStream: new (...args) => misc.IReadStream;
WriteStream: new (...args) => IWriteStream;
FSWatcher: new () => FSWatcher;
props: {
Node: new (...args) => Node;
Link: new (...args) => Link;
File: new (...args) => File;
};
private promisesApi = new FsPromises(this, FileHandle);
get promises(): FsPromisesApi {
if (this.promisesApi === null) throw new Error('Promise is not supported in this environment.');
return this.promisesApi;
}
constructor(props = {}) {
this.props = Object.assign({ Node, Link, File }, props);
const root = this.createLink();
root.setNode(this.createNode(constants.S_IFDIR | 0o777));
const self = this; // tslint:disable-line no-this-assignment
this.StatWatcher = class extends StatWatcher {
constructor() {
super(self);
}
};
const _ReadStream: new (...args) => misc.IReadStream = FsReadStream as any;
this.ReadStream = class extends _ReadStream {
constructor(...args) {
super(self, ...args);
}
} as any as new (...args) => misc.IReadStream;
const _WriteStream: new (...args) => IWriteStream = FsWriteStream as any;
this.WriteStream = class extends _WriteStream {
constructor(...args) {
super(self, ...args);
}
} as any as new (...args) => IWriteStream;
this.FSWatcher = class extends FSWatcher {
constructor() {
super(self);
}
};
root.setChild('.', root);
root.getNode().nlink++;
root.setChild('..', root);
root.getNode().nlink++;
this.root = root;
}
createLink(): Link;
createLink(parent: Link, name: string, isDirectory?: boolean, mode?: number): Link;
createLink(parent?: Link, name?: string, isDirectory: boolean = false, mode?: number): Link {
if (!parent) {
return new this.props.Link(this, null, '');
}
if (!name) {
throw new Error('createLink: name cannot be empty');
}
// If no explicit permission is provided, use defaults based on type
const finalPerm = mode ?? (isDirectory ? 0o777 : 0o666);
// To prevent making a breaking change, `mode` can also just be a permission number
// and the file type is set based on `isDirectory`
const hasFileType = mode && mode & constants.S_IFMT;
const modeType = hasFileType ? mode & constants.S_IFMT : isDirectory ? constants.S_IFDIR : constants.S_IFREG;
const finalMode = (finalPerm & ~constants.S_IFMT) | modeType;
return parent.createChild(name, this.createNode(finalMode));
}
deleteLink(link: Link): boolean {
const parent = link.parent;
if (parent) {
parent.deleteChild(link);
return true;
}
return false;
}
private newInoNumber(): number {
const releasedFd = this.releasedInos.pop();
if (releasedFd) return releasedFd;
else {
this.ino = (this.ino + 1) % 0xffffffff;
return this.ino;
}
}
private newFdNumber(): number {
const releasedFd = this.releasedFds.pop();
return typeof releasedFd === 'number' ? releasedFd : Volume.fd--;
}
createNode(mode: number): Node {
const node = new this.props.Node(this.newInoNumber(), mode);
this.inodes[node.ino] = node;
return node;
}
private deleteNode(node: Node) {
node.del();
delete this.inodes[node.ino];
this.releasedInos.push(node.ino);
}
private walk(
steps: string[],
resolveSymlinks: boolean,
checkExistence: boolean,
checkAccess: boolean,
funcName?: string,
): Link | null;
private walk(
filename: string,
resolveSymlinks: boolean,
checkExistence: boolean,
checkAccess: boolean,
funcName?: string,
): Link | null;
private walk(
link: Link,
resolveSymlinks: boolean,
checkExistence: boolean,
checkAccess: boolean,
funcName?: string,
): Link | null;
private walk(
stepsOrFilenameOrLink: string[] | string | Link,
resolveSymlinks: boolean,
checkExistence: boolean,
checkAccess: boolean,
funcName?: string,
): Link | null;
private walk(
stepsOrFilenameOrLink: string[] | string | Link,
resolveSymlinks: boolean = false,
checkExistence: boolean = false,
checkAccess: boolean = false,
funcName?: string,
): Link | null {
let steps: string[];
let filename: string;
if (stepsOrFilenameOrLink instanceof Link) {
steps = stepsOrFilenameOrLink.steps;
filename = sep + steps.join(sep);
} else if (typeof stepsOrFilenameOrLink === 'string') {
steps = filenameToSteps(stepsOrFilenameOrLink);
filename = stepsOrFilenameOrLink;
} else {
steps = stepsOrFilenameOrLink;
filename = sep + steps.join(sep);
}
let curr: Link | null = this.root;
let i = 0;
while (i < steps.length) {
let node: Node = curr.getNode();
// Check access permissions if current link is a directory
if (node.isDirectory()) {
if (checkAccess && !node.canExecute()) {
throw createError(EACCES, funcName, filename);
}
} else {
if (i < steps.length - 1) throw createError(ENOTDIR, funcName, filename);
}
curr = curr.getChild(steps[i]) ?? null;
// Check existence of current link
if (!curr)
if (checkExistence) throw createError(ENOENT, funcName, filename);
else return null;
node = curr?.getNode();
// Resolve symlink
if (resolveSymlinks && node.isSymlink()) {
const resolvedPath = pathModule.isAbsolute(node.symlink)
? node.symlink
: join(pathModule.dirname(curr.getPath()), node.symlink); // Relative to symlink's parent
steps = filenameToSteps(resolvedPath).concat(steps.slice(i + 1));
curr = this.root;
i = 0;
continue;
}
i++;
}
return curr;
}
// Returns a `Link` (hard link) referenced by path "split" into steps.
getLink(steps: string[]): Link | null {
return this.walk(steps, false, false, false);
}
// Just link `getLink`, but throws a correct user error, if link to found.
getLinkOrThrow(filename: string, funcName?: string): Link {
return this.walk(filename, false, true, true, funcName)!;
}
// Just like `getLink`, but also dereference/resolves symbolic links.
getResolvedLink(filenameOrSteps: string | string[]): Link | null {
return this.walk(filenameOrSteps, true, false, false);
}
// Just like `getLinkOrThrow`, but also dereference/resolves symbolic links.
getResolvedLinkOrThrow(filename: string, funcName?: string): Link {
return this.walk(filename, true, true, true, funcName)!;
}
resolveSymlinks(link: Link): Link | null {
return this.getResolvedLink(link.steps.slice(1));
}
// Just like `getLinkOrThrow`, but also verifies that the link is a directory.
private getLinkAsDirOrThrow(filename: string, funcName?: string): Link {
const link = this.getLinkOrThrow(filename, funcName)!;
if (!link.getNode().isDirectory()) throw createError(ENOTDIR, funcName, filename);
return link;
}
// Get the immediate parent directory of the link.
private getLinkParent(steps: string[]): Link | null {
return this.getLink(steps.slice(0, -1));
}
private getLinkParentAsDirOrThrow(filenameOrSteps: string | string[], funcName?: string): Link {
const steps: string[] = (
filenameOrSteps instanceof Array ? filenameOrSteps : filenameToSteps(filenameOrSteps)
).slice(0, -1);
const filename: string = sep + steps.join(sep);
const link = this.getLinkOrThrow(filename, funcName);
if (!link.getNode().isDirectory()) throw createError(ENOTDIR, funcName, filename);
return link;
}
private getFileByFd(fd: number): File {
return this.fds[String(fd)];
}
private getFileByFdOrThrow(fd: number, funcName?: string): File {
if (!isFd(fd)) throw TypeError(ERRSTR.FD);
const file = this.getFileByFd(fd);
if (!file) throw createError(EBADF, funcName);
return file;
}
/**
* @todo This is not used anymore. Remove.
*/
/*
private getNodeByIdOrCreate(id: TFileId, flags: number, perm: number): Node {
if (typeof id === 'number') {
const file = this.getFileByFd(id);
if (!file) throw Error('File nto found');
return file.node;
} else {
const steps = pathToSteps(id as PathLike);
let link = this.getLink(steps);
if (link) return link.getNode();
// Try creating a node if not found.
if (flags & O_CREAT) {
const dirLink = this.getLinkParent(steps);
if (dirLink) {
const name = steps[steps.length - 1];
link = this.createLink(dirLink, name, false, perm);
return link.getNode();
}
}
throw createError(ENOENT, 'getNodeByIdOrCreate', pathToFilename(id));
}
}
*/
private wrapAsync(method: (...args) => void, args: any[], callback: TCallback<any>) {
validateCallback(callback);
setImmediate(() => {
let result;
try {
result = method.apply(this, args);
} catch (err) {
callback(err);
return;
}
callback(null, result);
});
}
private _toJSON(link = this.root, json = {}, path?: string, asBuffer?: boolean): DirectoryJSON<string | null> {
let isEmpty = true;
let children = link.children;
if (link.getNode().isFile()) {
children = new Map([[link.getName(), link.parent.getChild(link.getName())]]);
link = link.parent;
}
for (const name of children.keys()) {
if (name === '.' || name === '..') {
continue;
}
isEmpty = false;
const child = link.getChild(name);
if (!child) {
throw new Error('_toJSON: unexpected undefined');
}
const node = child.getNode();
if (node.isFile()) {
let filename = child.getPath();
if (path) filename = relative(path, filename);
json[filename] = asBuffer ? node.getBuffer() : node.getString();
} else if (node.isDirectory()) {
this._toJSON(child, json, path, asBuffer);
}
}
let dirPath = link.getPath();
if (path) dirPath = relative(path, dirPath);
if (dirPath && isEmpty) {
json[dirPath] = null;
}
return json;
}
toJSON(paths?: PathLike | PathLike[], json = {}, isRelative = false, asBuffer = false): DirectoryJSON<string | null> {
const links: Link[] = [];
if (paths) {
if (!Array.isArray(paths)) paths = [paths];
for (const path of paths) {
const filename = pathToFilename(path);
const link = this.getResolvedLink(filename);
if (!link) continue;
links.push(link);
}
} else {
links.push(this.root);
}
if (!links.length) return json;
for (const link of links) this._toJSON(link, json, isRelative ? link.getPath() : '', asBuffer);
return json;
}
// TODO: `cwd` should probably not invoke `process.cwd()`.
fromJSON(json: DirectoryJSON, cwd: string = process.cwd()) {
for (let filename in json) {
const data = json[filename];
filename = resolve(filename, cwd);
if (typeof data === 'string' || data instanceof Buffer) {
const dir = dirname(filename);
this.mkdirpBase(dir, MODE.DIR);
this.writeFileSync(filename, data);
} else {
this.mkdirpBase(filename, MODE.DIR);
}
}
}
fromNestedJSON(json: NestedDirectoryJSON, cwd?: string) {
this.fromJSON(flattenJSON(json), cwd);
}
public toTree(opts: ToTreeOptions = { separator: <'/' | '\\'>sep }): string {
return toTreeSync(this, opts);
}
reset() {
this.ino = 0;
this.inodes = {};
this.releasedInos = [];
this.fds = {};
this.releasedFds = [];
this.openFiles = 0;
this.root = this.createLink();
this.root.setNode(this.createNode(constants.S_IFDIR | 0o777));
}
// Legacy interface
mountSync(mountpoint: string, json: DirectoryJSON) {
this.fromJSON(json, mountpoint);
}
private openLink(link: Link, flagsNum: number, resolveSymlinks: boolean = true): File {
if (this.openFiles >= this.maxFiles) {
// Too many open files.
throw createError(EMFILE, 'open', link.getPath());
}
// Resolve symlinks.
//
// @TODO: This should be superfluous. This method is only ever called by openFile(), which does its own symlink resolution
// prior to calling.
let realLink: Link | null = link;
if (resolveSymlinks) realLink = this.getResolvedLinkOrThrow(link.getPath(), 'open');
const node = realLink.getNode();
// Check whether node is a directory
if (node.isDirectory()) {
if ((flagsNum & (O_RDONLY | O_RDWR | O_WRONLY)) !== O_RDONLY) throw createError(EISDIR, 'open', link.getPath());
} else {
if (flagsNum & O_DIRECTORY) throw createError(ENOTDIR, 'open', link.getPath());
}
// Check node permissions
if (!(flagsNum & O_WRONLY)) {
if (!node.canRead()) {
throw createError(EACCES, 'open', link.getPath());
}
}
if (!(flagsNum & O_RDONLY)) {
if (!node.canWrite()) {
throw createError(EACCES, 'open', link.getPath());
}
}
const file = new this.props.File(link, node, flagsNum, this.newFdNumber());
this.fds[file.fd] = file;
this.openFiles++;
if (flagsNum & O_TRUNC) file.truncate();
return file;
}
private openFile(
filename: string,
flagsNum: number,
modeNum: number | undefined,
resolveSymlinks: boolean = true,
): File {
const steps = filenameToSteps(filename);
let link: Link | null;
try {
link = resolveSymlinks ? this.getResolvedLinkOrThrow(filename, 'open') : this.getLinkOrThrow(filename, 'open');
// Check if file already existed when trying to create it exclusively (O_CREAT and O_EXCL flags are set).
// This is an error, see https://pubs.opengroup.org/onlinepubs/009695399/functions/open.html:
// "If O_CREAT and O_EXCL are set, open() shall fail if the file exists."
if (link && flagsNum & O_CREAT && flagsNum & O_EXCL) throw createError(EEXIST, 'open', filename);
} catch (err) {
// Try creating a new file, if it does not exist and O_CREAT flag is set.
// Note that this will still throw if the ENOENT came from one of the
// intermediate directories instead of the file itself.
if (err.code === ENOENT && flagsNum & O_CREAT) {
const dirname: string = pathModule.dirname(filename);
const dirLink: Link = this.getResolvedLinkOrThrow(dirname);
const dirNode = dirLink.getNode();
// Check that the place we create the new file is actually a directory and that we are allowed to do so:
if (!dirNode.isDirectory()) throw createError(ENOTDIR, 'open', filename);
if (!dirNode.canExecute() || !dirNode.canWrite()) throw createError(EACCES, 'open', filename);
// This is a difference to the original implementation, which would simply not create a file unless modeNum was specified.
// However, current Node versions will default to 0o666.
modeNum ??= 0o666;
link = this.createLink(dirLink, steps[steps.length - 1], false, modeNum);
} else throw err;
}
if (link) return this.openLink(link, flagsNum, resolveSymlinks);
throw createError(ENOENT, 'open', filename);
}
private openBase(filename: string, flagsNum: number, modeNum: number, resolveSymlinks: boolean = true): number {
const file = this.openFile(filename, flagsNum, modeNum, resolveSymlinks);
if (!file) throw createError(ENOENT, 'open', filename);
return file.fd;
}
openSync(path: PathLike, flags: TFlags, mode: TMode = MODE.DEFAULT): number {
// Validate (1) mode; (2) path; (3) flags - in that order.
const modeNum = modeToNumber(mode);
const fileName = pathToFilename(path);
const flagsNum = flagsToNumber(flags);
return this.openBase(fileName, flagsNum, modeNum, !(flagsNum & O_SYMLINK));
}
open(path: PathLike, flags: TFlags, /* ... */ callback: TCallback<number>);
open(path: PathLike, flags: TFlags, mode: TMode, callback: TCallback<number>);
open(path: PathLike, flags: TFlags, a: TMode | TCallback<number>, b?: TCallback<number>) {
let mode: TMode = a as TMode;
let callback: TCallback<number> = b as TCallback<number>;
if (typeof a === 'function') {
mode = MODE.DEFAULT;
callback = a;
}
mode = mode || MODE.DEFAULT;
const modeNum = modeToNumber(mode);
const fileName = pathToFilename(path);
const flagsNum = flagsToNumber(flags);
this.wrapAsync(this.openBase, [fileName, flagsNum, modeNum, !(flagsNum & O_SYMLINK)], callback);
}
private closeFile(file: File) {
if (!this.fds[file.fd]) return;
this.openFiles--;
delete this.fds[file.fd];
this.releasedFds.push(file.fd);
}
closeSync(fd: number) {
validateFd(fd);
const file = this.getFileByFdOrThrow(fd, 'close');
this.closeFile(file);
}
close(fd: number, callback: TCallback<void>) {
validateFd(fd);
const file = this.getFileByFdOrThrow(fd, 'close');
// NOTE: not calling closeSync because we can reset in between close and closeSync
this.wrapAsync(this.closeFile, [file], callback);
}
private openFileOrGetById(id: TFileId, flagsNum: number, modeNum?: number): File {
if (typeof id === 'number') {
const file = this.fds[id];
if (!file) throw createError(ENOENT);
return file;
} else {
return this.openFile(pathToFilename(id), flagsNum, modeNum);
}
}
private readBase(
fd: number,
buffer: Buffer | ArrayBufferView | DataView,
offset: number,
length: number,
position: number | null,
): number {
if (buffer.byteLength < length) {
throw createError(ERR_OUT_OF_RANGE, 'read', undefined, undefined, RangeError);
}
const file = this.getFileByFdOrThrow(fd);
if (file.node.isSymlink()) {
throw createError(EPERM, 'read', file.link.getPath());
}
return file.read(
buffer,
Number(offset),
Number(length),
position === -1 || typeof position !== 'number' ? undefined : position,
);
}
readSync(
fd: number,
buffer: Buffer | ArrayBufferView | DataView,
offset: number,
length: number,
position: number | null,
): number {
validateFd(fd);
return this.readBase(fd, buffer, offset, length, position);
}
read(
fd: number,
buffer: Buffer | ArrayBufferView | DataView,
offset: number,
length: number,
position: number | null,
callback: (err?: Error | null, bytesRead?: number, buffer?: Buffer | ArrayBufferView | DataView) => void,
) {
validateCallback(callback);
// This `if` branch is from Node.js
if (length === 0) {
return queueMicrotask(() => {
if (callback) callback(null, 0, buffer);
});
}
setImmediate(() => {
try {
const bytes = this.readBase(fd, buffer, offset, length, position);
callback(null, bytes, buffer);
} catch (err) {
callback(err);
}
});
}
private readvBase(fd: number, buffers: ArrayBufferView[], position: number | null): number {
const file = this.getFileByFdOrThrow(fd);
let p = position ?? undefined;
if (p === -1) {
p = undefined;
}
let bytesRead = 0;
for (const buffer of buffers) {
const bytes = file.read(buffer, 0, buffer.byteLength, p);
p = undefined;
bytesRead += bytes;
if (bytes < buffer.byteLength) break;
}
return bytesRead;
}
readv(fd: number, buffers: ArrayBufferView[], callback: misc.TCallback2<number, ArrayBufferView[]>): void;
readv(
fd: number,
buffers: ArrayBufferView[],
position: number | null,
callback: misc.TCallback2<number, ArrayBufferView[]>,
): void;
readv(
fd: number,
buffers: ArrayBufferView[],
a: number | null | misc.TCallback2<number, ArrayBufferView[]>,
b?: misc.TCallback2<number, ArrayBufferView[]>,
): void {
let position: number | null = a as number | null;
let callback: misc.TCallback2<number, ArrayBufferView[]> = b as misc.TCallback2<number, ArrayBufferView[]>;
if (typeof a === 'function') {
position = null;
callback = a;
}
validateCallback(callback);
setImmediate(() => {
try {
const bytes = this.readvBase(fd, buffers, position);
callback(null, bytes, buffers);
} catch (err) {
callback(err);
}
});
}
readvSync(fd: number, buffers: ArrayBufferView[], position: number | null): number {
validateFd(fd);
return this.readvBase(fd, buffers, position);
}
private readFileBase(id: TFileId, flagsNum: number, encoding: BufferEncoding): Buffer | string {
let result: Buffer | string;
const isUserFd = typeof id === 'number';
const userOwnsFd: boolean = isUserFd && isFd(id);
let fd: number;
if (userOwnsFd) fd = id as number;
else {
const filename = pathToFilename(id as PathLike);
const link: Link = this.getResolvedLinkOrThrow(filename, 'open');
const node = link.getNode();
if (node.isDirectory()) throw createError(EISDIR, 'open', link.getPath());
fd = this.openSync(id as PathLike, flagsNum);
}
try {
result = bufferToEncoding(this.getFileByFdOrThrow(fd).getBuffer(), encoding);
} finally {
if (!userOwnsFd) {
this.closeSync(fd);
}
}
return result;
}
readFileSync(file: TFileId, options?: opts.IReadFileOptions | string): TDataOut {
const opts = getReadFileOptions(options);
const flagsNum = flagsToNumber(opts.flag);
return this.readFileBase(file, flagsNum, opts.encoding as BufferEncoding);
}
readFile(id: TFileId, callback: TCallback<TDataOut>);
readFile(id: TFileId, options: opts.IReadFileOptions | string, callback: TCallback<TDataOut>);
readFile(id: TFileId, a: TCallback<TDataOut> | opts.IReadFileOptions | string, b?: TCallback<TDataOut>) {
const [opts, callback] = optsAndCbGenerator<opts.IReadFileOptions, TCallback<TDataOut>>(getReadFileOptions)(a, b);
const flagsNum = flagsToNumber(opts.flag);