/
binding.js
1506 lines (1377 loc) · 44.5 KB
/
binding.js
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
'use strict';
const path = require('path');
const File = require('./file');
const FileDescriptor = require('./descriptor');
const Directory = require('./directory');
const SymbolicLink = require('./symlink');
const FSError = require('./error');
const constants = require('constants');
const getPathParts = require('./filesystem').getPathParts;
const bufferFrom = require('./buffer').from;
const bufferAlloc = require('./buffer').alloc;
const MODE_TO_KTYPE = {
[constants.S_IFREG]: constants.UV_DIRENT_FILE,
[constants.S_IFDIR]: constants.UV_DIRENT_DIR,
[constants.S_IFBLK]: constants.UV_DIRENT_BLOCK,
[constants.S_IFCHR]: constants.UV_DIRENT_CHAR,
[constants.S_IFLNK]: constants.UV_DIRENT_LINK,
[constants.S_IFIFO]: constants.UV_DIRENT_FIFO,
[constants.S_IFSOCK]: constants.UV_DIRENT_SOCKET
};
/** Workaround for optimizations in node 8+ */
const fsBinding = process.binding('fs');
const kUsePromises = fsBinding.kUsePromises;
let statValues;
if (fsBinding.statValues) {
statValues = fsBinding.statValues; // node 10+
} else if (fsBinding.getStatValues) {
statValues = fsBinding.getStatValues(); // node 8
} else {
statValues = [];
}
// nodejs v6,8,10 and v12 before v12.10.0 has length 28
// nodejs v12.10.0+ has length 36
const statContainsNs = statValues.length > 28;
/** Introduction of BigUint64Array in 10.5 */
let BigUint64Array;
if (global.BigUint64Array) {
BigUint64Array = global.BigUint64Array;
} else {
BigUint64Array = function() {};
}
const MAX_LINKS = 50;
/**
* Call the provided function and either return the result or call the callback
* with it (depending on if a callback is provided).
* @param {function()} callback Optional callback.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @param {Object} thisArg This argument for the following function.
* @param {function()} func Function to call.
* @return {*} Return (if callback is not provided).
*/
function maybeCallback(callback, ctx, thisArg, func) {
let err = null;
let val;
if (kUsePromises && callback === kUsePromises) {
// support nodejs v10+ fs.promises
try {
val = func.call(thisArg);
} catch (e) {
err = e;
}
return new Promise(function(resolve, reject) {
process.nextTick(function() {
if (err) {
reject(err);
} else {
resolve(val);
}
});
});
} else if (callback && typeof callback === 'function') {
try {
val = func.call(thisArg);
} catch (e) {
err = e;
}
process.nextTick(function() {
if (val === undefined) {
callback(err);
} else {
callback(err, val);
}
});
} else if (ctx && typeof ctx === 'object') {
try {
return func.call(thisArg);
} catch (e) {
// default to errno for UNKNOWN
ctx.code = e.code || 'UNKNOWN';
ctx.errno = e.errno || FSError.codes.UNKNOWN.errno;
}
} else {
return func.call(thisArg);
}
}
/**
* set syscall property on context object, only for nodejs v10+.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @param {String} syscall Name of syscall.
*/
function markSyscall(ctx, syscall) {
if (ctx && typeof ctx === 'object') {
ctx.syscall = syscall;
}
}
/**
* Handle FSReqWrap oncomplete.
* @param {Function} callback The callback.
* @return {Function} The normalized callback.
*/
function normalizeCallback(callback) {
if (callback && typeof callback.oncomplete === 'function') {
// Unpack callback from FSReqWrap
callback = callback.oncomplete.bind(callback);
}
return callback;
}
/**
* Handle stat optimizations introduced in Node 8.
* See https://github.com/nodejs/node/pull/11665.
* @param {Function} callback The callback.
* @return {Function} The wrapped callback.
*/
function wrapStatsCallback(callback) {
if (callback && typeof callback.oncomplete === 'function') {
// Unpack callback from FSReqWrap
callback = callback.oncomplete.bind(callback);
}
if (typeof callback === 'function') {
return function(err, stats) {
if (stats) {
fillStatsArray(stats, statValues);
}
callback.apply(this, arguments);
};
} else {
return callback;
}
}
function getDirentType(mode) {
const ktype = MODE_TO_KTYPE[mode & constants.S_IFMT];
if (ktype === undefined) {
return constants.UV_DIRENT_UNKNOWN;
}
return ktype;
}
function notImplemented() {
throw new Error('Method not implemented');
}
/**
* Create a new stats object.
* @param {Object} config Stats properties.
* @constructor
*/
function Stats(config) {
for (const key in config) {
this[key] = config[key];
}
// node 10 expects an array internally
// see https://github.com/nodejs/node/pull/19714
fillStatsArray(config, this);
}
/**
* Check if mode indicates property.
* @param {number} property Property to check.
* @return {boolean} Property matches mode.
*/
Stats.prototype._checkModeProperty = function(property) {
return (this.mode & constants.S_IFMT) === property;
};
/**
* @return {Boolean} Is a directory.
*/
Stats.prototype.isDirectory = function() {
return this._checkModeProperty(constants.S_IFDIR);
};
/**
* @return {Boolean} Is a regular file.
*/
Stats.prototype.isFile = function() {
return this._checkModeProperty(constants.S_IFREG);
};
/**
* @return {Boolean} Is a block device.
*/
Stats.prototype.isBlockDevice = function() {
return this._checkModeProperty(constants.S_IFBLK);
};
/**
* @return {Boolean} Is a character device.
*/
Stats.prototype.isCharacterDevice = function() {
return this._checkModeProperty(constants.S_IFCHR);
};
/**
* @return {Boolean} Is a symbolic link.
*/
Stats.prototype.isSymbolicLink = function() {
return this._checkModeProperty(constants.S_IFLNK);
};
/**
* @return {Boolean} Is a named pipe.
*/
Stats.prototype.isFIFO = function() {
return this._checkModeProperty(constants.S_IFIFO);
};
/**
* @return {Boolean} Is a socket.
*/
Stats.prototype.isSocket = function() {
return this._checkModeProperty(constants.S_IFSOCK);
};
// I don't know exactly what is going on.
// If _openFiles is a property of binding instance, there is a strange
// bug in nodejs v10+ that something cleaned up this._openFiles from
// nowhere. It happens after second mockfs(), after first mockfs()+restore().
// So I moved _openFiles to a private var. The other two vars (_system,
// _counter) do not hurt.
// This fixed https://github.com/tschaub/mock-fs/issues/254
// But I did not dig deep enough to understand what exactly happened.
let _system;
let _openFiles = {};
let _counter = 0;
/**
* Create a new binding with the given file system.
* @param {FileSystem} system Mock file system.
* @constructor
*/
function Binding(system) {
/**
* Mock file system.
* @type {FileSystem}
*/
_system = system;
/**
* Stats constructor.
* @type {function}
*/
this.Stats = Stats;
/**
* Lookup of open files.
* @type {Object.<number, FileDescriptor>}
*/
_openFiles = {};
/**
* Counter for file descriptors.
* @type {number}
*/
_counter = 0;
}
/**
* Get the file system underlying this binding.
* @return {FileSystem} The underlying file system.
*/
Binding.prototype.getSystem = function() {
return _system;
};
/**
* Reset the file system underlying this binding.
* @param {FileSystem} system The new file system.
*/
Binding.prototype.setSystem = function(system) {
_system = system;
};
/**
* Get a file descriptor.
* @param {number} fd File descriptor identifier.
* @return {FileDescriptor} File descriptor.
*/
function getDescriptorById(fd) {
if (!_openFiles.hasOwnProperty(fd)) {
throw new FSError('EBADF');
}
return _openFiles[fd];
}
/**
* Keep track of a file descriptor as open.
* @param {FileDescriptor} descriptor The file descriptor.
* @return {number} Identifier for file descriptor.
*/
function trackDescriptor(descriptor) {
const fd = ++_counter;
_openFiles[fd] = descriptor;
return fd;
}
/**
* Stop tracking a file descriptor as open.
* @param {number} fd Identifier for file descriptor.
*/
function untrackDescriptorById(fd) {
if (!_openFiles.hasOwnProperty(fd)) {
throw new FSError('EBADF');
}
delete _openFiles[fd];
}
/**
* Resolve the canonicalized absolute pathname.
* @param {string|Buffer} filepath The file path.
* @param {string} encoding The encoding for the return.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {string|Buffer} The real path.
*/
Binding.prototype.realpath = function(filepath, encoding, callback, ctx) {
markSyscall(ctx, 'realpath');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
let realPath;
if (Buffer.isBuffer(filepath)) {
filepath = filepath.toString();
}
const resolved = path.resolve(filepath);
const parts = getPathParts(resolved);
let item = _system.getRoot();
let itemPath = '/';
let name, i, ii;
for (i = 0, ii = parts.length; i < ii; ++i) {
name = parts[i];
while (item instanceof SymbolicLink) {
itemPath = path.resolve(path.dirname(itemPath), item.getPath());
item = _system.getItem(itemPath);
}
if (!item) {
throw new FSError('ENOENT', filepath);
}
if (item instanceof Directory) {
itemPath = path.resolve(itemPath, name);
item = item.getItem(name);
} else {
throw new FSError('ENOTDIR', filepath);
}
}
if (item) {
while (item instanceof SymbolicLink) {
itemPath = path.resolve(path.dirname(itemPath), item.getPath());
item = _system.getItem(itemPath);
}
realPath = itemPath;
} else {
throw new FSError('ENOENT', filepath);
}
if (process.platform === 'win32' && realPath.startsWith('\\\\?\\')) {
// Remove win32 file namespace prefix \\?\
realPath = realPath.slice(4);
}
if (encoding === 'buffer') {
realPath = bufferFrom(realPath);
}
return realPath;
});
};
/**
* Fill a Float64Array with stat information
* This is based on the internal FillStatsArray function in Node.
* https://github.com/nodejs/node/blob/4e05952a8a75af6df625415db612d3a9a1322682/src/node_file.cc#L533
* @param {Object} stats An object with file stats
* @param {Float64Array} statValues A Float64Array where stat values should be inserted
* @returns {void}
*/
function fillStatsArray(stats, statValues) {
statValues[0] = stats.dev;
statValues[1] = stats.mode;
statValues[2] = stats.nlink;
statValues[3] = stats.uid;
statValues[4] = stats.gid;
statValues[5] = stats.rdev;
statValues[6] = stats.blksize;
statValues[7] = stats.ino;
statValues[8] = stats.size;
statValues[9] = stats.blocks;
if (statContainsNs) {
// nodejs v12.10.0+
// This is based on the internal FillStatsArray function in Node.
// https://github.com/nodejs/node/blob/3a2e75d9a5c31d20e429d505b82dd182e33f459a/src/node_file.h#L153-L187
statValues[10] = Math.floor(stats.atimeMs / 1000);
statValues[11] = (stats.atimeMs % 1000) * 1000000;
statValues[12] = Math.floor(stats.mtimeMs / 1000);
statValues[13] = (stats.mtimeMs % 1000) * 1000000;
statValues[14] = Math.floor(stats.ctimeMs / 1000);
statValues[15] = (stats.ctimeMs % 1000) * 1000000;
statValues[16] = Math.floor(stats.birthtimeMs / 1000);
statValues[17] = (stats.birthtimeMs % 1000) * 1000000;
} else {
// nodejs before v12.10.0
// This is based on the internal FillStatsArray function in Node.
// https://github.com/nodejs/node/blob/4e05952a8a75af6df625415db612d3a9a1322682/src/node_file.cc#L533
statValues[10] = stats.atimeMs;
statValues[11] = stats.mtimeMs;
statValues[12] = stats.ctimeMs;
statValues[13] = stats.birthtimeMs;
}
}
/**
* Stat an item.
* @param {string} filepath Path.
* @param {function(Error, Stats)|Float64Array|BigUint64Array} callback Callback (optional). In Node 7.7.0+ this will be a Float64Array
* that should be filled with stat values.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {Stats|undefined} Stats or undefined (if sync).
*/
Binding.prototype.stat = function(filepath, options, callback, ctx) {
// this seems wound not happen in nodejs v10+
if (arguments.length < 3) {
callback = options;
options = {};
}
markSyscall(ctx, 'stat');
return maybeCallback(wrapStatsCallback(callback), ctx, this, function() {
let item = _system.getItem(filepath);
if (item instanceof SymbolicLink) {
item = _system.getItem(
path.resolve(path.dirname(filepath), item.getPath())
);
}
if (!item) {
throw new FSError('ENOENT', filepath);
}
const stats = item.getStats();
// In Node 7.7.0+, binding.stat accepts a Float64Array as the second argument,
// which should be filled with stat values.
// In prior versions of Node, binding.stat simply returns a Stats instance.
if (
callback instanceof Float64Array ||
callback instanceof BigUint64Array
) {
fillStatsArray(stats, callback);
} else {
fillStatsArray(stats, statValues);
return new Stats(stats);
}
});
};
/**
* Stat an item.
* @param {number} fd File descriptor.
* @param {function(Error, Stats)|Float64Array|BigUint64Array} callback Callback (optional). In Node 7.7.0+ this will be a Float64Array
* that should be filled with stat values.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {Stats|undefined} Stats or undefined (if sync).
*/
Binding.prototype.fstat = function(fd, options, callback, ctx) {
if (arguments.length < 3) {
callback = options;
options = {};
}
markSyscall(ctx, 'fstat');
return maybeCallback(wrapStatsCallback(callback), ctx, this, function() {
const descriptor = getDescriptorById(fd);
const item = descriptor.getItem();
const stats = item.getStats();
// In Node 7.7.0+, binding.stat accepts a Float64Array as the second argument,
// which should be filled with stat values.
// In prior versions of Node, binding.stat simply returns a Stats instance.
if (
callback instanceof Float64Array ||
callback instanceof BigUint64Array
) {
fillStatsArray(stats, callback);
} else {
fillStatsArray(stats, statValues);
return new Stats(stats);
}
});
};
/**
* Close a file descriptor.
* @param {number} fd File descriptor.
* @param {function(Error)} callback Callback (optional).
* @param {Object} ctx Context object (optional), only for nodejs v10+.
*/
Binding.prototype.close = function(fd, callback, ctx) {
markSyscall(ctx, 'close');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
untrackDescriptorById(fd);
});
};
/**
* Open and possibly create a file.
* @param {string} pathname File path.
* @param {number} flags Flags.
* @param {number} mode Mode.
* @param {function(Error, string)} callback Callback (optional).
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {string} File descriptor (if sync).
*/
Binding.prototype.open = function(pathname, flags, mode, callback, ctx) {
markSyscall(ctx, 'open');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
const descriptor = new FileDescriptor(flags);
let item = _system.getItem(pathname);
while (item instanceof SymbolicLink) {
item = _system.getItem(
path.resolve(path.dirname(pathname), item.getPath())
);
}
if (descriptor.isExclusive() && item) {
throw new FSError('EEXIST', pathname);
}
if (descriptor.isCreate() && !item) {
const parent = _system.getItem(path.dirname(pathname));
if (!parent) {
throw new FSError('ENOENT', pathname);
}
if (!(parent instanceof Directory)) {
throw new FSError('ENOTDIR', pathname);
}
item = new File();
if (mode) {
item.setMode(mode);
}
parent.addItem(path.basename(pathname), item);
}
if (descriptor.isRead()) {
if (!item) {
throw new FSError('ENOENT', pathname);
}
if (!item.canRead()) {
throw new FSError('EACCES', pathname);
}
}
if (descriptor.isWrite() && !item.canWrite()) {
throw new FSError('EACCES', pathname);
}
if (
item instanceof Directory &&
(descriptor.isTruncate() || descriptor.isAppend())
) {
throw new FSError('EISDIR', pathname);
}
if (descriptor.isTruncate()) {
if (!(item instanceof File)) {
throw new FSError('EBADF');
}
item.setContent('');
}
if (descriptor.isTruncate() || descriptor.isAppend()) {
descriptor.setPosition(item.getContent().length);
}
descriptor.setItem(item);
return trackDescriptor(descriptor);
});
};
/**
* Open a file handler. A new api in nodejs v10+ for fs.promises
* @param {string} pathname File path.
* @param {number} flags Flags.
* @param {number} mode Mode.
* @param {function} callback Callback (optional), expecting kUsePromises in nodejs v10+.
*/
Binding.prototype.openFileHandle = function(pathname, flags, mode, callback) {
const self = this;
return this.open(pathname, flags, mode, kUsePromises).then(function(fd) {
// nodejs v10+ fs.promises FileHandler constructor only ask these three properties.
return {
getAsyncId: notImplemented,
fd: fd,
close: function() {
return self.close(fd, kUsePromises);
}
};
});
};
/**
* Read from a file descriptor.
* @param {string} fd File descriptor.
* @param {Buffer} buffer Buffer that the contents will be written to.
* @param {number} offset Offset in the buffer to start writing to.
* @param {number} length Number of bytes to read.
* @param {?number} position Where to begin reading in the file. If null,
* data will be read from the current file position.
* @param {function(Error, number, Buffer)} callback Callback (optional) called
* with any error, number of bytes read, and the buffer.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {number} Number of bytes read (if sync).
*/
Binding.prototype.read = function(
fd,
buffer,
offset,
length,
position,
callback,
ctx
) {
markSyscall(ctx, 'read');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
const descriptor = getDescriptorById(fd);
if (!descriptor.isRead()) {
throw new FSError('EBADF');
}
const file = descriptor.getItem();
if (file instanceof Directory) {
throw new FSError('EISDIR');
}
if (!(file instanceof File)) {
// deleted or not a regular file
throw new FSError('EBADF');
}
if (typeof position !== 'number' || position < 0) {
position = descriptor.getPosition();
}
const content = file.getContent();
const start = Math.min(position, content.length);
const end = Math.min(position + length, content.length);
const read = start < end ? content.copy(buffer, offset, start, end) : 0;
descriptor.setPosition(position + read);
return read;
});
};
/**
* Write to a file descriptor given a buffer.
* @param {string} src Source file.
* @param {string} dest Destination file.
* @param {number} flags Modifiers for copy operation.
* @param {function(Error)} callback Callback (optional) called
* with any error.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
*/
Binding.prototype.copyFile = function(src, dest, flags, callback, ctx) {
markSyscall(ctx, 'copyfile');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
const srcFd = this.open(src, constants.O_RDONLY);
try {
const srcDescriptor = getDescriptorById(srcFd);
if (!srcDescriptor.isRead()) {
throw new FSError('EBADF');
}
const srcFile = srcDescriptor.getItem();
if (!(srcFile instanceof File)) {
throw new FSError('EBADF');
}
const srcContent = srcFile.getContent();
let destFlags =
constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC;
if ((flags & constants.COPYFILE_EXCL) === constants.COPYFILE_EXCL) {
destFlags |= constants.O_EXCL;
}
const destFd = this.open(dest, destFlags);
try {
this.write(destFd, srcContent, 0, srcContent.length, 0);
} finally {
this.close(destFd);
}
} finally {
this.close(srcFd);
}
});
};
/**
* Write to a file descriptor given a buffer.
* @param {string} fd File descriptor.
* @param {Array<Buffer>} buffers Array of buffers with contents to write.
* @param {?number} position Where to begin writing in the file. If null,
* data will be written to the current file position.
* @param {function(Error, number, Buffer)} callback Callback (optional) called
* with any error, number of bytes written, and the buffer.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {number} Number of bytes written (if sync).
*/
Binding.prototype.writeBuffers = function(
fd,
buffers,
position,
callback,
ctx
) {
markSyscall(ctx, 'write');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
const descriptor = getDescriptorById(fd);
if (!descriptor.isWrite()) {
throw new FSError('EBADF');
}
const file = descriptor.getItem();
if (!(file instanceof File)) {
// not a regular file
throw new FSError('EBADF');
}
if (typeof position !== 'number' || position < 0) {
position = descriptor.getPosition();
}
let content = file.getContent();
const newContent = Buffer.concat(buffers);
const newLength = position + newContent.length;
if (content.length < newLength) {
const tempContent = bufferAlloc(newLength);
content.copy(tempContent);
content = tempContent;
}
const written = newContent.copy(content, position);
file.setContent(content);
descriptor.setPosition(newLength);
return written;
});
};
/**
* Write to a file descriptor given a buffer.
* @param {string} fd File descriptor.
* @param {Buffer} buffer Buffer with contents to write.
* @param {number} offset Offset in the buffer to start writing from.
* @param {number} length Number of bytes to write.
* @param {?number} position Where to begin writing in the file. If null,
* data will be written to the current file position.
* @param {function(Error, number, Buffer)} callback Callback (optional) called
* with any error, number of bytes written, and the buffer.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {number} Number of bytes written (if sync).
*/
Binding.prototype.writeBuffer = function(
fd,
buffer,
offset,
length,
position,
callback,
ctx
) {
markSyscall(ctx, 'write');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
const descriptor = getDescriptorById(fd);
if (!descriptor.isWrite()) {
throw new FSError('EBADF');
}
const file = descriptor.getItem();
if (!(file instanceof File)) {
// not a regular file
throw new FSError('EBADF');
}
if (typeof position !== 'number' || position < 0) {
position = descriptor.getPosition();
}
let content = file.getContent();
const newLength = position + length;
if (content.length < newLength) {
const newContent = bufferAlloc(newLength);
content.copy(newContent);
content = newContent;
}
const sourceEnd = Math.min(offset + length, buffer.length);
const written = bufferFrom(buffer).copy(
content,
position,
offset,
sourceEnd
);
file.setContent(content);
descriptor.setPosition(newLength);
return written;
});
};
/**
* Alias for writeBuffer (used in Node <= 0.10).
* @param {string} fd File descriptor.
* @param {Buffer} buffer Buffer with contents to write.
* @param {number} offset Offset in the buffer to start writing from.
* @param {number} length Number of bytes to write.
* @param {?number} position Where to begin writing in the file. If null,
* data will be written to the current file position.
* @param {function(Error, number, Buffer)} callback Callback (optional) called
* with any error, number of bytes written, and the buffer.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {number} Number of bytes written (if sync).
*/
Binding.prototype.write = Binding.prototype.writeBuffer;
/**
* Write to a file descriptor given a string.
* @param {string} fd File descriptor.
* @param {string} string String with contents to write.
* @param {number} position Where to begin writing in the file. If null,
* data will be written to the current file position.
* @param {string} encoding String encoding.
* @param {function(Error, number, string)} callback Callback (optional) called
* with any error, number of bytes written, and the string.
* @return {number} Number of bytes written (if sync).
*/
Binding.prototype.writeString = function(
fd,
string,
position,
encoding,
callback,
ctx
) {
markSyscall(ctx, 'write');
const buffer = bufferFrom(string, encoding);
let wrapper;
if (callback && callback !== kUsePromises) {
if (callback.oncomplete) {
callback = callback.oncomplete.bind(callback);
}
wrapper = function(err, written, returned) {
callback(err, written, returned && string);
};
}
return this.writeBuffer(fd, buffer, 0, string.length, position, wrapper, ctx);
};
/**
* Rename a file.
* @param {string} oldPath Old pathname.
* @param {string} newPath New pathname.
* @param {function(Error)} callback Callback (optional).
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {undefined}
*/
Binding.prototype.rename = function(oldPath, newPath, callback, ctx) {
markSyscall(ctx, 'rename');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
const oldItem = _system.getItem(oldPath);
if (!oldItem) {
throw new FSError('ENOENT', oldPath);
}
const oldParent = _system.getItem(path.dirname(oldPath));
const oldName = path.basename(oldPath);
const newItem = _system.getItem(newPath);
const newParent = _system.getItem(path.dirname(newPath));
const newName = path.basename(newPath);
if (newItem) {
// make sure they are the same type
if (oldItem instanceof File) {
if (newItem instanceof Directory) {
throw new FSError('EISDIR', newPath);
}
} else if (oldItem instanceof Directory) {
if (!(newItem instanceof Directory)) {
throw new FSError('ENOTDIR', newPath);
}
if (newItem.list().length > 0) {
throw new FSError('ENOTEMPTY', newPath);
}
}
newParent.removeItem(newName);
} else {
if (!newParent) {
throw new FSError('ENOENT', newPath);
}
if (!(newParent instanceof Directory)) {
throw new FSError('ENOTDIR', newPath);
}
}
oldParent.removeItem(oldName);
newParent.addItem(newName, oldItem);
});
};
/**
* Read a directory.
* @param {string} dirpath Path to directory.
* @param {string} encoding The encoding ('utf-8' or 'buffer').
* @param {boolean} withFileTypes whether or not to return fs.Dirent objects
* @param {function(Error, (Array.<string>|Array.<Buffer>)} callback Callback
* (optional) called with any error or array of items in the directory.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
* @return {Array.<string>|Array.<Buffer>} Array of items in directory (if sync).
*/
Binding.prototype.readdir = function(
dirpath,
encoding,
withFileTypes,
callback,
ctx
) {
// again, the shorter arguments would not happen in nodejs v10+
if (arguments.length === 2) {
callback = encoding;
encoding = 'utf-8';
} else if (arguments.length === 3) {
callback = withFileTypes;
}
markSyscall(ctx, 'scandir');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
let dpath = dirpath;
let dir = _system.getItem(dirpath);
while (dir instanceof SymbolicLink) {
dpath = path.resolve(path.dirname(dpath), dir.getPath());
dir = _system.getItem(dpath);
}
if (!dir) {
throw new FSError('ENOENT', dirpath);
}
if (!(dir instanceof Directory)) {
throw new FSError('ENOTDIR', dirpath);
}
if (!dir.canRead()) {
throw new FSError('EACCES', dirpath);
}
let list = dir.list();
if (encoding === 'buffer') {
list = list.map(function(item) {
return bufferFrom(item);
});
}
if (withFileTypes === true) {
const types = list.map(function(name) {
const stats = dir.getItem(name).getStats();
return getDirentType(stats.mode);
});
list = [list, types];
}
return list;
});
};
/**
* Create a directory.
* @param {string} pathname Path to new directory.
* @param {number} mode Permissions.
* @param {boolean} recursive Recursively create deep directory. (added in nodejs v10+)
* @param {function(Error)} callback Optional callback.
* @param {Object} ctx Context object (optional), only for nodejs v10+.
*/
Binding.prototype.mkdir = function(pathname, mode, recursive, callback, ctx) {
if (typeof recursive !== 'boolean') {
// when running nodejs < 10
ctx = callback;
callback = recursive;
recursive = false;
}
markSyscall(ctx, 'mkdir');
return maybeCallback(normalizeCallback(callback), ctx, this, function() {
const item = _system.getItem(pathname);
if (item) {