@@ -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 ) ;
@@ -498,7 +513,7 @@ async function rename(oldPath, newPath) {
498513
499514async function truncate ( path , len = 0 ) {
500515 const fd = await open ( path , 'r+' ) ;
501- return PromisePrototypeFinally ( ftruncate ( fd , len ) , fd . close ) ;
516+ return handleFdClose ( ftruncate ( fd , len ) , fd . close ) ;
502517}
503518
504519async function ftruncate ( handle , len = 0 ) {
@@ -629,7 +644,7 @@ async function lchmod(path, mode) {
629644 throw new ERR_METHOD_NOT_IMPLEMENTED ( 'lchmod()' ) ;
630645
631646 const fd = await open ( path , O_WRONLY | O_SYMLINK ) ;
632- return PromisePrototypeFinally ( fchmod ( fd , mode ) , fd . close ) ;
647+ return handleFdClose ( fchmod ( fd , mode ) , fd . close ) ;
633648}
634649
635650async function lchown ( path , uid , gid ) {
@@ -708,7 +723,7 @@ async function writeFile(path, data, options) {
708723 checkAborted ( options . signal ) ;
709724
710725 const fd = await open ( path , flag , options . mode ) ;
711- return PromisePrototypeFinally (
726+ return handleFdClose (
712727 writeFileHandle ( fd , data , options . signal , options . encoding ) , fd . close ) ;
713728}
714729
@@ -733,7 +748,7 @@ async function readFile(path, options) {
733748 checkAborted ( options . signal ) ;
734749
735750 const fd = await open ( path , flag , 0o666 ) ;
736- return PromisePrototypeFinally ( readFileHandle ( fd , options ) , fd . close ) ;
751+ return handleFdClose ( readFileHandle ( fd , options ) , fd . close ) ;
737752}
738753
739754module . exports = {
0 commit comments