@@ -33,6 +33,7 @@ const {
33
33
ERR_METHOD_NOT_IMPLEMENTED ,
34
34
} ,
35
35
AbortError,
36
+ aggregateTwoErrors,
36
37
} = require ( 'internal/errors' ) ;
37
38
const { isArrayBufferView } = require ( 'internal/util/types' ) ;
38
39
const { rimrafPromises } = require ( 'internal/fs/rimraf' ) ;
@@ -250,6 +251,27 @@ class FileHandle extends EventEmitterMixin(JSTransferable) {
250
251
}
251
252
}
252
253
254
+ async function handleFdClose ( fileOpPromise , closeFunc ) {
255
+ let opError ;
256
+ try {
257
+ return await fileOpPromise ;
258
+ } catch ( err ) {
259
+ opError = err ;
260
+ throw err ;
261
+ } finally {
262
+ try {
263
+ await closeFunc ( ) ;
264
+ } catch ( closeError ) {
265
+ if ( ! opError ) {
266
+ // eslint-disable-next-line no-unsafe-finally
267
+ throw closeError ;
268
+ }
269
+ // eslint-disable-next-line no-unsafe-finally
270
+ throw aggregateTwoErrors ( closeError , opError ) ;
271
+ }
272
+ }
273
+ }
274
+
253
275
async function fsCall ( fn , handle , ...args ) {
254
276
if ( handle [ kRefs ] === undefined ) {
255
277
throw new ERR_INVALID_ARG_TYPE ( 'filehandle' , 'FileHandle' , handle ) ;
@@ -498,7 +520,7 @@ async function rename(oldPath, newPath) {
498
520
499
521
async function truncate ( path , len = 0 ) {
500
522
const fd = await open ( path , 'r+' ) ;
501
- return PromisePrototypeFinally ( ftruncate ( fd , len ) , fd . close ) ;
523
+ return handleFdClose ( ftruncate ( fd , len ) , fd . close ) ;
502
524
}
503
525
504
526
async function ftruncate ( handle , len = 0 ) {
@@ -629,7 +651,7 @@ async function lchmod(path, mode) {
629
651
throw new ERR_METHOD_NOT_IMPLEMENTED ( 'lchmod()' ) ;
630
652
631
653
const fd = await open ( path , O_WRONLY | O_SYMLINK ) ;
632
- return PromisePrototypeFinally ( fchmod ( fd , mode ) , fd . close ) ;
654
+ return handleFdClose ( fchmod ( fd , mode ) , fd . close ) ;
633
655
}
634
656
635
657
async function lchown ( path , uid , gid ) {
@@ -708,7 +730,7 @@ async function writeFile(path, data, options) {
708
730
checkAborted ( options . signal ) ;
709
731
710
732
const fd = await open ( path , flag , options . mode ) ;
711
- return PromisePrototypeFinally (
733
+ return handleFdClose (
712
734
writeFileHandle ( fd , data , options . signal , options . encoding ) , fd . close ) ;
713
735
}
714
736
@@ -733,7 +755,7 @@ async function readFile(path, options) {
733
755
checkAborted ( options . signal ) ;
734
756
735
757
const fd = await open ( path , flag , 0o666 ) ;
736
- return PromisePrototypeFinally ( readFileHandle ( fd , options ) , fd . close ) ;
758
+ return handleFdClose ( readFileHandle ( fd , options ) , fd . close ) ;
737
759
}
738
760
739
761
module . exports = {
0 commit comments