-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
1455 lines (1229 loc) · 41.5 KB
/
index.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
(function (global, factory) {
typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('buffer'), require('stream'), require('events'), require('util')) :
typeof define === 'function' && define.amd ? define(['exports', 'buffer', 'stream', 'events', 'util'], factory) :
(factory((global['uwp-fs'] = {}),global.buffer,global.stream,global.events,global.util));
}(this, (function (exports,buffer,stream,EventEmitter,util) { 'use strict';
EventEmitter = EventEmitter && EventEmitter.hasOwnProperty('default') ? EventEmitter['default'] : EventEmitter;
util = util && util.hasOwnProperty('default') ? util['default'] : util;
if (typeof process$1 === 'undefined')
var process$1 = {};
if (typeof process$1.nextTick === 'undefined')
process$1.nextTick = (fn, ...args) => setTimeout(() => fn(...args));
var isUwp = typeof Windows !== 'undefined';
var readyPromises = [];
var ready = new Promise(resolve => {
setTimeout(() => {
Promise.all(readyPromises).then(resolve);
});
});
function wrapPromise(promise) {
return new Promise((resolve, reject) => promise.then(resolve, reject))
}
function callbackify(promiseOrFunction, callback) {
if (callback === undefined) {
return (...args) => {
if (typeof args[args.length - 1] === 'function')
return _callbackify(promiseOrFunction(...args), args.pop())
else
return _callbackify(promiseOrFunction(...args))
}
} else {
return _callbackify(promiseOrFunction, callback)
}
}
function _callbackify(promise, callback) {
if (callback) {
promise
.then(data => callback(null, data))
.catch(err => process$1.nextTick(callback, err));
//.catch(err => callback(err))
}
return promise
}
// Strips drive name from path (creates path relative to the drive)
function stripDrive(path) {
var index;
index = path.indexOf(':\\\\');
if ((index = path.indexOf(':\\\\')) !== -1)
path = path.substr(index + 3);
if ((index = path.indexOf(':\\')) !== -1)
path = path.substr(index + 2);
return path
}
function extractDrive(path) {
var index = path.indexOf(':');
return path.substr(index - 1, index).toLowerCase()
}
// Tests UWP StorageFolder if it's just a random folder or a drive (like C:\)
function isFolderDrive(folder) {
return folder.name === folder.path && folder.path.endsWith(':\\')
}
// todo investigate deprecation
function getOptions(options, defaultOptions = {}) {
if (options === null || options === undefined || typeof options === 'function')
return defaultOptions
if (typeof options === 'string')
return Object.assign({}, defaultOptions, {encoding: options})
else if (typeof options === 'object')
return Object.assign({}, options, defaultOptions)
}
// todo deprecate
function maybeCallback$1(cb) {
return typeof cb === 'function' ? cb : rethrow();
}
function nullCheck(path) {
if (('' + path).indexOf('\u0000') !== -1)
throw new errors.Error('ERR_INVALID_ARG_TYPE', 'path', 'string without null bytes', path)
}
// refference:
// win: https://github.com/nodejs/node/blob/master/deps/uv/include/uv-errno.h
// unix: https://github.com/nodejs/node/blob/master/deps/npm/node_modules/worker-farm/node_modules/errno/errno.js
// https://nodejs.org/en/blog/release/v9.0.0/
var ERROR = {
UNKNOWN: {
errno: -1,
code: 'UNKNOWN',
description: 'unknown error'
},
UNKNOWN_UWP: {
errno: -1,
code: 'UNKNOWN_UWP',
description: 'unknown uwp error'
},
// NOTE: there are two ENOENTs, one with errno -2, second with errno 34 (according to node files)
// testing proved that the -2 is used in unix, -4058 in windows, 34 is not.
ENOENT: {
errno: -4058, // -2
code: 'ENOENT',
description: 'no such file or directory'
},
EACCES: {
errno: -4092, // 3
code: 'EACCES',
description: 'permission denied'
},
EADDRINUSE: {
errno: -4091, // 5
code: 'EADDRINUSE',
description: 'address already in use'
},
EINVAL: {
errno: -4071, // 18
code: 'EINVAL',
description: 'invalid argument'
},
ENOTDIR: {
errno: -4052, // 27
code: 'ENOTDIR',
description: 'not a directory'
},
EISDIR: {
errno: -4068, // 28
code: 'EISDIR',
description: 'illegal operation on a directory'
},
EEXIST: {
errno: -4075, // 47
code: 'EEXIST',
description: 'file already exists'
},
EPERM: {
errno: -4048, // 50
code: 'EPERM',
description: 'operation not permitted'
},
ENOTEMPTY: {
errno: -4051, // 53
code: 'ENOTEMPTY',
description: 'directory not empty'
}
};
// todo: rename this because its custom errno function and not the one found in fs
function syscallException(error, syscall, path) {
if (error instanceof Error) {
var {errno, code} = ERROR.UNKNOWN_UWP;
var err = error;
} else {
if (typeof error === 'string')
error = ERROR[error];
var {errno, code, description} = error;
var message = `${code}: ${description}, ${syscall}`;
if (path)
message += ` '${path}'`;
var err = new Error(message);
}
err.errno = errno;
err.code = code;
err.syscall = syscall;
if (path)
err.path = path;
return err
}
var UWP_ERR = {
ENOENT: 'The system cannot find the file specified.\r\n',
EACCES: 'Access is denied.\r\n',
_INCORRECT: 'The parameter is incorrect.\r\n',
_UNSUPPORTED: 'No such interface supported\r\n',
};
// TODO
var errors$1 = {
TypeError: makeNodeError(TypeError),
RangeError: makeNodeError(RangeError),
Error: makeNodeError(Error),
};
function makeNodeError(Err) {
// TODO
return Err
}
;
var installFolder;
var dataFolder;
;
if (isUwp) {
// Path to local installation of the app.
// App's source code (what the project includes) is there
// If sideloaded it's in \bin\Debug\AppX of the folder where the Visual Studio project is.
// Windows.ApplicationModel.Package.current.installedLocation
installFolder = Windows.ApplicationModel.Package.current.installedLocation;
// Path to %AppData%\Local\Packages\{id}\LocalState
// It's empty and app's data can be stored there
// Windows.Storage.ApplicationData.current.localFolder
dataFolder = Windows.Storage.ApplicationData.current.localFolder;
let subPath = location
.pathname
.slice(1) // remove first slash
.split('/') // split into sections by slashes
.slice(0, -1) // remove the last section (html filename)
.join('\\'); // join by windows style backslash
exports.cwd = installFolder.path + '\\' + subPath;
var promise = installFolder.getFolderAsync(subPath)
.then(folder => exports.cwdFolder = folder);
readyPromises.push(promise);
}
async function uwpSetCwd(newCwd) {
exports.cwd = newCwd;
var path = getPathFromURL(exports.cwd);
exports.cwdFolder = await Windows.Storage.StorageFolder.getFolderFromPathAsync(path);
}
function uwpSetCwdFolder(newFolder) {
exports.cwdFolder = newFolder;
exports.cwd = exports.cwdFolder.path;
}
// Windows filesystem uses \ instead of /. Node tolerates that, but UWP apis
// strictly require only \ or they'll throw error.
// Normalizes path by stripping unnecessary slashes and adding drive letter if needed
function getPathFromURL(path) {
// Strip spaces around and convert all slashes to windows backslashes
path = path.trim().replace(/\//g, '\\');
// convert absolute paths to absolute C:\ paths
if (path.startsWith('\\'))
path = 'C:' + path;
else if (!path.includes(':\\'))
path = exports.cwd + '\\' + path;
// Normalize the path
var normalized = normalizeArray(path.split(/\\+/g)).join('\\');
if (normalized.endsWith(':'))
return normalized + '\\'
else
return normalized
}
function normalizeArray(parts) {
var res = [];
for (var i = 0; i < parts.length; i++) {
var p = parts[i];
if (!p || p === '.')
continue
if (p === '..') {
if (res.length && res[res.length - 1] !== '..')
res.pop();
} else {
res.push(p);
}
}
return res
}
function relativize(path, relativeTo = exports.cwd) {
return path.slice(relativeTo.length + 1)
}
function dirname(path) {
var sections = path.split('\\');
sections.pop();
return sections.join('\\')
}
if (isUwp) {
var {StorageFolder: StorageFolder$1, StorageFile: StorageFile$1} = Windows.Storage;
}
async function openStorageObject(path, syscall) {
// Sanitize backslashes, normalize format, and turn the path into absolute path.
path = getPathFromURL(path);
// Go straight to StorageFolder resolution if the path points to a drive.
if (path.endsWith(':\\'))
return _openStorageFolder(path, syscall)
// Get the folder object that corresponds to absolute path in the file system.
try {
return await StorageFile$1.getFileFromPathAsync(path)
} catch(err) {
if (err.message == UWP_ERR.ENOENT || err.message === UWP_ERR._INCORRECT || err.message === UWP_ERR._UNSUPPORTED) {
return _openStorageFolder(path, syscall)
} else {
throw processError(err, syscall, path)
}
}
}
async function _openStorageFolder(path, syscall) {
// Get the folder object that corresponds to absolute path in the file system.
try {
return await StorageFolder$1.getFolderFromPathAsync(path)
} catch(err) {
throw processError(err, syscall, path)
}
}
async function openStorageFolder(path, syscall) {
// Sanitize backslashes, normalize format, and turn the path into absolute path.
path = getPathFromURL(path);
// Get the folder object that corresponds to absolute path in the file system.
try {
return await StorageFolder$1.getFolderFromPathAsync(path)
} catch(err) {
switch (err.message) {
// The path is incorrect or the file/folder is missing.
case UWP_ERR.ENOENT:
throw syscallException('ENOENT', syscall, path)
// UWP does not have permission to access this scope.
case UWP_ERR.EACCES:
throw syscallException('EACCES', syscall, path)
default:
var storageFile;
try {
storageFile = await StorageFile$1.getFileFromPathAsync(path);
} catch(e) {
throw processError(err, syscall, path)
}
throw syscallException('ENOTDIR', syscall, path)
}
}
}
async function openStorageFile(path, syscall) {
// Sanitize backslashes, normalize format, and turn the path into absolute path.
path = getPathFromURL(path);
// Get the file object that corresponds to absolute path in the file system.
try {
return await StorageFile$1.getFileFromPathAsync(path)
} catch(err) {
throw processError(err, syscall, path)
}
}
// Translates UWP errors into Node format (with code, errno and path)
function processError(err, syscall, path, storageObjectType) {
// Compare UWP error messages with list of known meanings
switch (err.message) {
// The path is incorrect or the file/folder is missing.
case UWP_ERR.ENOENT:
throw syscallException('ENOENT', syscall, path)
// UWP does not have permission to access this scope.
case UWP_ERR.EACCES:
throw syscallException('EACCES', syscall, path)
// Incorrect parameter is usually thrown when trying to open folder as file and vice versa.
/*case UWP_ERR._INCORRECT:
if (storageObjectType === 'folder') {
throw syscallException('ENOTDIR', syscall, path)
break
}*/
default:
throw syscallException(err, syscall, path)
}
}
if (isUwp) {
var {StorageFolder, StorageFile, FileAccessMode} = Windows.Storage;
var {DataReader, DataWriter, InputStreamOptions} = Windows.Storage.Streams;
}
// List of active File Descriptors.
// First three FDs are taken by stdin, stdout, stderr (and are inaccessible in UWP).
// Warning: If process uses more than three basic FDs (like forked process with 'ipc' channel)
// than the first number of FDs won't match (this module will always start at fd 3)
var fds = [null, null, null];
function findEmpyFd() {
for (var i = 2; i < fds.length; i++)
if (fds[i] === undefined) return i
return fds.length
}
function clearFd(fd) {
if (fd === fds.length - 1)
fds.length--;
else if (fd < fds.length)
fds[fd] = undefined;
}
function reserveFd() {
var fd = findEmpyFd();
fds[fd] = null;
return fd
}
/*
'r' Open file for reading. An exception occurs if the file does not exist.
'r+' Open file for reading and writing. An exception occurs if the file does not exist.
'rs+' Open file for reading and writing in synchronous mode. Instructs the operating system to bypass the local file system cache.
'w' Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
'wx' Like 'w' but fails if path exists.
'w+' Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists).
'wx+' Like 'w+' but fails if path exists.
'a' Open file for appending. The file is created if it does not exist.
'ax' Like 'a' but fails if path exists.
'a+' Open file for reading and appending. The file is created if it does not exist.
'ax+' Like 'a+' but fails if path exists.
*/
async function _open(fd, path, flags = 'r', mode = 0o666) {
// Access UWP's File object
// Note: Not wrapped in try/catching because openStorageObject() returns sanitized Node-like error object.
var storageObject = await openStorageObject(path, 'open');
var folder, file, stream$$1, reader, writer;
if (storageObject.constructor === StorageFolder)
folder = storageObject;
if (storageObject.constructor === StorageFile)
file = storageObject;
if (file !== undefined) {
// Open file's read stream
// TODO: wrap in try/catch and handle errors
stream$$1 = await storageObject.openAsync(FileAccessMode.read);
if (!window.iStream)
window.iStream = stream$$1;
if (flags.includes('r')) {
var reader = new DataReader(stream$$1);
reader.inputStreamOptions = InputStreamOptions.partial;
}
if (flags === 'r+')
writer = 'TODO';
//FileAccessMode.read
//FileAccessMode.readWrite
}
return {file, folder, storageObject, stream: stream$$1, reader, writer, path}
}
var open = callbackify(async (path, flags, mode) => {
// Create absolute path and check for corrections (it thows proper Node-like error otherwise)
path = getPathFromURL(path);
nullCheck(path);
// we need to reserve fd ahead of async operations to prevent collisions
var fd = reserveFd();
// Try to do the actual opening
try {
// Store all storage objects if opening succeeded (file or folder at given path exists)
fds[fd] = await _open(fd, path, flags, mode);
} catch(err) {
// Otherwise close the fd and propragate captured error.
clearFd(fd);
throw err
}
// Open returns fd number we can alter use to access the storage objects
return fd
});
/*
export var open = callbackify(async (path, flags = 'r', mode = 0o666) => {
// Create absolute path and check for corrections (it thows proper Node-like error otherwise)
path = getPathFromURL(path)
nullCheck(path)
// we need to reserve fd ahead of async operations to prevent collisions
var fd = reserveFd()
// Access UWP's File object
// Note: Not wrapped in try/catching because openStorageObject() returns sanitized Node-like error object.
var storageObject = await openStorageObject(path, 'open')
var folder, file, stream, reader, writer
if (storageObject.constructor === StorageFolder)
folder = storageObject
if (storageObject.constructor === StorageFile)
file = storageObject
if (file !== undefined) {
// Open file's read stream
// TODO: wrap in try/catch and handle errors
stream = await storageObject.openAsync(FileAccessMode.read)
if (!window.iStream)
window.iStream = stream
if (flags.includes('r')) {
var reader = new DataReader(stream)
reader.inputStreamOptions = InputStreamOptions.partial
}
if (flags === 'r+')
writer = 'TODO'
//FileAccessMode.read
//FileAccessMode.readWrite
}
fds[fd] = {file, folder, storageObject, stream, reader, writer, path}
return fd
})
*/
var unlink = callbackify(async path => {
// Create absolute path and check for corrections (it thows proper Node-like error otherwise)
path = getPathFromURL(path);
nullCheck(path);
// Access UWP's StorageFile object
// Note: Not wrapped in try/catching because openStorageObject() returns sanitized Node-like error object.
var storageObject = await openStorageObject(path, 'unlink');
if (storageObject.constructor === StorageFolder)
throw syscallException('EPERM', 'unlink', path)
await storageObject.deleteAsync();
});
var mkdir = callbackify(async path => {
// Create absolute path and check for corrections (it thows proper Node-like error otherwise)
path = getPathFromURL(path);
nullCheck(path);
// Get path to parent folder.
var parentPath = dirname(path);
// NOTE: Can't use open() or openStorageFolder() because mkdir throws slightly different errors.
try {
var parentFolder = await StorageFolder.getFolderFromPathAsync(parentPath);
} catch(err) {
// NOTE: we really need to return whole 'path' despite asking for 'parentpath'
throw syscallException('ENOENT', 'mkdir', path)
}
// Try to get object on given path and throw error if something exists.
try {
var storageObject = await openStorageObject(path, 'mkdir');
} catch(err) {}
if (storageObject)
throw syscallException('EEXIST', 'mkdir', path)
// All clear, we can proceed to create the folder.
var foldername = relativize(path, parentPath);
await parentFolder.createFolderAsync(foldername);
});
var rmdir = callbackify(async path => {
// Create absolute path and check for corrections (it thows proper Node-like error otherwise)
path = getPathFromURL(path);
nullCheck(path);
// Access UWP's StorageFolder object
// Note: Not wrapped in try/catching because openStorageObject() returns sanitized Node-like error object.
var storageObject = await openStorageObject(path, 'rmdir');
// Throw errors if there's file a file of the same name, or if the folder has content-
if (storageObject.constructor === StorageFile)
throw syscallException('ENOENT', 'rmdir', path)
var children = await storageObject.getItemsAsync();
if (children.length > 0)
throw syscallException('ENOTEMPTY', 'rmdir', path)
// No errors, the folder is empty, delete it.
await storageObject.deleteAsync();
});
/*
Read data from the file specified by 'fd'.
'buffer' is the buffer that the data will be written to.
'offset' is the offset in the buffer to start writing at.
'length' is an integer specifying the number of bytes to read.
'position' is an argument specifying where to begin reading from in the file. If position is null, data will be read from the current file position, and the file position will be updated. If position is an integer, the file position will remain unchanged.
The callback is given the three arguments, '(err, bytesRead, buffer)'.
*/
async function _read(fd, buffer$$1, offset, length, position) {
// NOTE: Order of these errors matter. Do not change.
if (buffer$$1 === undefined || !Buffer.isBuffer(buffer$$1))
throw new errors$1.TypeError('Second argument needs to be a buffer')
// note: position -1 means don't move to any position, start reading where we left off last time.
if (position < -1)
throw syscallException('EINVAL', 'read')
if (offset < 0 || offset > buffer$$1.length)
throw new errors$1.Error('Offset is out of bounds')
if (offset + length > buffer$$1.length)
throw new errors$1.RangeError('Length extends beyond buffer')
var {file, folder, stream: stream$$1, reader} = fds[fd];
if (file === undefined && folder !== undefined)
throw syscallException('EISDIR', 'read')
if (position > stream$$1.size)
return {bytesRead: 0, buffer: buffer$$1}
// Set position where to begin reading from in the file.
if (position !== null && position !== -1)
stream$$1.seek(position);
// Assess the ammount of bytes we want to read.
//var bytesToRead = length || stream.size
var bytesToRead = Math.min(stream$$1.size - position, length);
// Request to read that ammount of bytes, but but ready to comply to UWP's restictions.
var bytesRead = await reader.loadAsync(bytesToRead);
//var bytesRead = reader.unconsumedBufferLength
var view = buffer$$1.slice(offset, offset + bytesRead);
//var view = buffer.slice(offset, offset + length)
//var view = Buffer.allocUnsafe(bytesRead)
// Now that UWP loaded the bytes for use, we can read them into our buffer.
reader.readBytes(view);
return {bytesRead, buffer: buffer$$1}
}
// NOTE: not using callbackify() because Node's fs.read() when wrapped in Node's util.promisify()
// returns different things.
// - Callback has error and two arguments (instead of just one): bytesRead, buffer
// - Promise returns an object with bytesRead and buffer properties: {bytesRead, buffer}
function read(fd, buffer$$1, offset, length, position, callback) {
var promise = _read(fd, buffer$$1, offset, length, position);
if (callback) {
promise
.then(({bytesRead, buffer: buffer$$1}) => callback(null, bytesRead, buffer$$1))
.catch(err => callback(err));
}
return promise
}
//await storageFolder.CreateFileAsync("sample.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);
var close = callbackify(async fd => {
var content = fds[fd];
if (typeof fd === 'number') clearFd(fd);
if (!content) return
var {file, folder, stream: stream$$1, reader, writer} = content;
// TODO
if (reader)
reader.close();
if (writer)
writer.close();
// Note: C# has .Dispose(), JS has .close() variant
if (stream$$1)
stream$$1.close();
});
var exists = callbackify(async path => {
// Create absolute path and check for corrections (it thows proper Node-like error otherwise)
path = getPathFromURL(path);
nullCheck(path);
try {
await openStorageObject(path);
return true
} catch(err) {
if (err.code !== 'ENOENT')
throw err
return false
}
});
var stat = callbackify(async path => {
// Create absolute path and check for corrections (it thows proper Node-like error otherwise)
path = getPathFromURL(path);
nullCheck(path);
// Access UWP's storage object
// Note: Not wrapped in try/catching because openStorageObject() returns sanitized Node-like error object.
var storageObject = await openStorageObject(path, 'stat');
// Create Stats instance, wait for the hidden ready promise (UWP apis are async) and return it
var stats = new Stats(storageObject);
await stats._ready;
return stats
});
const DATE_ACCESSED = 'System.DateAccessed';
// time "Access Time" - Time when file data last accessed.
// mtime "Modified Time" - Time when file data last modified.
// ctime "Change Time" - Time when file status was last changed
class Stats {
constructor(storageObject) {
this.storageObject = storageObject;
Object.defineProperty(this, '_ready', {
enumerable: false,
value: this._collectInfo()
});
}
async _collectInfo() {
var file = this.storageObject;
var {dateCreated} = file;
this.birthtime = dateCreated;
this.birthtimeMs = dateCreated.valueOf();
// Get basic properties
var {size, dateModified} = await file.getBasicPropertiesAsync();
this.size = size;
this.mtime = this.ctime = dateModified;
this.mtimeMs = this.ctimeMs = dateModified.valueOf();
// Get extra properties
var extraProperties = await file.properties.retrievePropertiesAsync([DATE_ACCESSED])
.then(data => Object.assign({}, data));
var dateAccessed = extraProperties[DATE_ACCESSED];
this.atime = dateAccessed;
this.atimeMs = dateAccessed.valueOf();
}
isFile() {
return this.storageObject.constructor === StorageFile
}
isDirectory() {
return this.storageObject.constructor === StorageFolder
}
isBlockDevice() {
}
isCharacterDevice() {
}
isSymbolicLink() {
}
isFIFO() {
}
isSocket() {
}
}
var readdir = callbackify(async path => {
// Access StorageFolder directly, because readdir doesn't use .open() and FDs
var folder = await openStorageFolder(path, 'scandir');
return (await folder.getItemsAsync())
.map(file => file.name)
.sort(caseInsensitiveSort)
});
function caseInsensitiveSort(a, b) {
a = a.toLowerCase();
b = b.toLowerCase();
if (a == b) return 0
if (a > b) return 1
return -1
}
var defaultReadStreamOptions = {
highWaterMark: 64 * 1024,
fd: null,
flags: 'r',
mode: 0o666,
autoClose: true,
};
var defaultWriteStreamOptions = {
fd: null,
flags: 'w',
mode: 0o666,
autoClose: true,
};
var pool;
function allocNewPool(poolSize) {
pool = Buffer.allocUnsafe(poolSize);
pool.used = 0;
}
class ReadStream extends stream.Readable {
constructor(path, options = {}) {
options = Object.assign({}, defaultReadStreamOptions, options);
super(options);
this.path = getPathFromURL(path);
Object.assign(this, options);
this.pos = undefined;
this.bytesRead = 0;
if (this.start !== undefined) {
if (typeof this.start !== 'number') {
throw new errors$1.TypeError('ERR_INVALID_ARG_TYPE', 'start', 'number', this.start)
}
if (this.end === undefined) {
this.end = Infinity;
} else if (typeof this.end !== 'number') {
throw new errors$1.TypeError('ERR_INVALID_ARG_TYPE', 'end', 'number', this.end)
}
if (this.start > this.end) {
const errVal = `{start: ${this.start}, end: ${this.end}}`;
throw new errors$1.RangeError('ERR_VALUE_OUT_OF_RANGE', 'start', '<= "end"', errVal)
}
this.pos = this.start;
}
if (typeof this.fd !== 'number')
this.open();
this.on('end', function() {
if (this.autoClose)
this.destroy();
});
}
open() {
open(this.path, this.flags, this.mode)
.then(fd => {
this.fd = fd;
this.emit('open', fd);
// Start the flow of data.
this.read();
})
.catch(err => {
if (this.autoClose)
this.destroy();
this.emit('error', err);
});
}
_read(n) {
if (typeof this.fd !== 'number')
return this.once('open', () => this._read(n))
if (this.destroyed)
return
// Discard the old pool.
if (!pool || pool.length - pool.used < kMinPoolSpace)
allocNewPool(this._readableState.highWaterMark);
// Grab another reference to the pool in the case that while we're
// in the thread pool another read() finishes up the pool, and
// allocates a new one.
var thisPool = pool;
var toRead = Math.min(pool.length - pool.used, n);
var start = pool.used;
if (this.pos !== undefined)
toRead = Math.min(this.end - this.pos + 1, toRead);
// Elready read everything we were supposed to read! Treat as EOF.
if (toRead <= 0)
return this.push(null)
// The actual read.
read(this.fd, pool, pool.used, toRead, this.pos)
.then(bytesRead => {
var b = null;
if (bytesRead > 0) {
this.bytesRead += bytesRead;
b = thisPool.slice(start, start + bytesRead);
}
this.push(b);
})
.catch(er => {
if (this.autoClose)
this.destroy();
this.emit('error', er);
});
// Move the pool positions, and internal position for reading.
if (this.pos !== undefined)
this.pos += toRead;
pool.used += toRead;
}
_destroy(err, cb) {
if (this.closed || typeof this.fd !== 'number') {
if (typeof this.fd !== 'number') {
this.once('open', closeFsStream.bind(null, this, cb, err));
return
}
return process.nextTick(() => {
cb(err);
this.emit('close');
})
}
this.closed = true;
closeFsStream(this, cb);
this.fd = null;
}
}
class WriteStream extends stream.Writable {
constructor(path, options = {}) {
options = Object.assign({}, options);
super(options);
this.path = getPathFromURL(path);
Object.assign(this, options);
this.pos = undefined;
this.bytesWritten = 0;
if (this.start !== undefined) {
if (typeof this.start !== 'number') {
throw new errors$1.TypeError('ERR_INVALID_ARG_TYPE', 'start', 'number', this.start)
}
if (this.start < 0) {
const errVal = `{start: ${this.start}}`;
throw new errors$1.RangeError('ERR_VALUE_OUT_OF_RANGE', 'start', '>= 0', errVal)
}
this.pos = this.start;
}
if (options.encoding)
this.setDefaultEncoding(options.encoding);
if (typeof this.fd !== 'number')
this.open();
// dispose on finish.
this.once('finish', function() {
if (this.autoClose)
this.destroy();
});
}
// TODO
}
if (ReadStream.prototype.destroy === undefined)
ReadStream.prototype.destroy = ReadStream.prototype.close;
if (WriteStream.prototype.destroy === undefined)
WriteStream.prototype.destroy = WriteStream.prototype.end;
function closeFsStream(stream$$1, cb, err) {
close(stream$$1.fd)
.catch(() => stream$$1.emit('close'))
.catch(er => cb(er || err));
}
if (isUwp) {
var {FileIO} = Windows.Storage;
var {DataReader: DataReader$1, DataWriter: DataWriter$1} = Windows.Storage.Streams;
var COLLISION = Windows.Storage.CreationCollisionOption;
}
var readFile = callbackify(async (path, options) => {
// NOTE: it's really 'flag' and not 'flags' like it's in fs.open
options = getOptions(options, {encoding: null, flag: 'r'});
var isUserFd = isFd(path);
var fd = isUserFd ? path : await open(path, options.flag);
// Access descriptor to avoid creating an fs.Stats instance for our internal use.
var {stream: stream$$1} = fds[fd];
// Get the size of the file (or folder).
var size = stream$$1 ? stream$$1.size : 0;
// Throw errors if the size is invalid.
//if (size === 0)
// return Buffer.alloc(0)
if (size > buffer.kMaxLength) {
err = new RangeError('File size is greater than possible Buffer: ' + `0x${buffer.kMaxLength.toString(16)} bytes`);
close(fd);
throw err
}
try {
// Try to allocate enough memory for the size of the file.
var buffer$$1 = buffer.Buffer.allocUnsafe(size);
// Read (repeatedly if needed) the file into previously allocated buffer.
var offset = 0;
// Do at least one iteration (even for folders) because read syscall can handle and fire additional errors.
do {
let {bytesRead} = await _read(fd, buffer$$1, offset, size, -1);
offset += bytesRead;
// Break the loop in case we're unable to read anything.
if (bytesRead === 0)
break
} while (offset < size)
} catch (err) {
// All the errors received here should be already in the Node-like format and we can