@@ -10,6 +10,7 @@ const {
1010 PromisePrototypeFinally,
1111 PromisePrototypeThen,
1212 PromiseResolve,
13+ PromiseReject,
1314 SafeArrayIterator,
1415 Symbol,
1516 Uint8Array,
@@ -33,6 +34,7 @@ const {
3334 ERR_METHOD_NOT_IMPLEMENTED ,
3435 } ,
3536 AbortError,
37+ aggregateTwoErrors,
3638} = require ( 'internal/errors' ) ;
3739const { isArrayBufferView } = require ( 'internal/util/types' ) ;
3840const { rimrafPromises } = require ( 'internal/fs/rimraf' ) ;
@@ -250,6 +252,19 @@ class FileHandle extends EventEmitterMixin(JSTransferable) {
250252 }
251253}
252254
255+ async function handleFdClose ( fileOpPromise , closeFunc ) {
256+ return PromisePrototypeThen (
257+ fileOpPromise ,
258+ ( result ) => PromisePrototypeThen ( closeFunc ( ) , ( ) => result ) ,
259+ ( opError ) =>
260+ PromisePrototypeThen (
261+ closeFunc ( ) ,
262+ ( ) => PromiseReject ( opError ) ,
263+ ( closeError ) => PromiseReject ( aggregateTwoErrors ( closeError , opError ) )
264+ )
265+ ) ;
266+ }
267+
253268async function fsCall ( fn , handle , ...args ) {
254269 if ( handle [ kRefs ] === undefined ) {
255270 throw new ERR_INVALID_ARG_TYPE ( 'filehandle' , 'FileHandle' , handle ) ;
@@ -501,7 +516,7 @@ async function rename(oldPath, newPath) {
501516
502517async function truncate ( path , len = 0 ) {
503518 const fd = await open ( path , 'r+' ) ;
504- return PromisePrototypeFinally ( ftruncate ( fd , len ) , fd . close ) ;
519+ return handleFdClose ( ftruncate ( fd , len ) , fd . close ) ;
505520}
506521
507522async function ftruncate ( handle , len = 0 ) {
@@ -632,7 +647,7 @@ async function lchmod(path, mode) {
632647 throw new ERR_METHOD_NOT_IMPLEMENTED ( 'lchmod()' ) ;
633648
634649 const fd = await open ( path , O_WRONLY | O_SYMLINK ) ;
635- return PromisePrototypeFinally ( fchmod ( fd , mode ) , fd . close ) ;
650+ return handleFdClose ( fchmod ( fd , mode ) , fd . close ) ;
636651}
637652
638653async function lchown ( path , uid , gid ) {
@@ -711,7 +726,7 @@ async function writeFile(path, data, options) {
711726 checkAborted ( options . signal ) ;
712727
713728 const fd = await open ( path , flag , options . mode ) ;
714- return PromisePrototypeFinally (
729+ return handleFdClose (
715730 writeFileHandle ( fd , data , options . signal , options . encoding ) , fd . close ) ;
716731}
717732
@@ -736,7 +751,7 @@ async function readFile(path, options) {
736751 checkAborted ( options . signal ) ;
737752
738753 const fd = await open ( path , flag , 0o666 ) ;
739- return PromisePrototypeFinally ( readFileHandle ( fd , options ) , fd . close ) ;
754+ return handleFdClose ( readFileHandle ( fd , options ) , fd . close ) ;
740755}
741756
742757module . exports = {
0 commit comments