22
33const common = require ( '../common' ) ;
44const fs = require ( 'fs' ) ;
5+ const os = require ( 'os' ) ;
6+ const cp = require ( 'child_process' ) ;
57const fsPromises = fs . promises ;
68const path = require ( 'path' ) ;
79const tmpdir = require ( '../common/tmpdir' ) ;
@@ -11,7 +13,9 @@ const tmpDir = tmpdir.path;
1113tmpdir . refresh ( ) ;
1214
1315const dest = path . resolve ( tmpDir , 'tmp.txt' ) ;
14- const otherDest = path . resolve ( tmpDir , 'tmp-2.txt' ) ;
16+ const otherDest2 = path . resolve ( tmpDir , 'tmp-2.txt' ) ;
17+ const otherDest3 = path . resolve ( tmpDir , 'tmp-3.txt' ) ;
18+ const otherDest4 = path . resolve ( tmpDir , 'tmp-4.txt' ) ;
1519const buffer = Buffer . from ( 'abc' . repeat ( 1000 ) ) ;
1620const buffer2 = Buffer . from ( 'xyz' . repeat ( 1000 ) ) ;
1721
@@ -25,9 +29,33 @@ async function doWriteWithCancel() {
2529 const controller = new AbortController ( ) ;
2630 const { signal } = controller ;
2731 process . nextTick ( ( ) => controller . abort ( ) ) ;
28- assert . rejects ( fsPromises . writeFile ( otherDest , buffer , { signal } ) , {
32+ assert . rejects ( fsPromises . writeFile ( otherDest2 , buffer , { signal } ) , {
2933 name : 'AbortError'
30- } ) ;
34+ } ) . then ( common . mustCall ( ( ) => {
35+ checkIfFileIsOpen ( otherDest2 ) ;
36+ } ) ) ;
37+ }
38+
39+ async function doWriteWithCancelPreSync ( ) {
40+ const controller = new AbortController ( ) ;
41+ const { signal } = controller ;
42+ controller . abort ( ) ;
43+ assert . rejects ( fsPromises . writeFile ( otherDest3 , buffer , { signal } ) , {
44+ name : 'AbortError'
45+ } ) . then ( common . mustCall ( ( ) => {
46+ checkIfFileIsOpen ( otherDest3 ) ;
47+ } ) ) ;
48+ }
49+
50+ async function doWriteWithCancelPostSync ( ) {
51+ const controller = new AbortController ( ) ;
52+ const { signal } = controller ;
53+ controller . abort ( ) ;
54+ assert . rejects ( fsPromises . writeFile ( otherDest4 , buffer , { signal } ) , {
55+ name : 'AbortError'
56+ } ) . then ( common . mustCall ( ( ) => {
57+ checkIfFileIsOpen ( otherDest4 ) ;
58+ } ) ) ;
3159}
3260
3361async function doAppend ( ) {
@@ -55,4 +83,21 @@ doWrite()
5583 . then ( doAppend )
5684 . then ( doRead )
5785 . then ( doReadWithEncoding )
86+ . then ( doWriteWithCancelPreSync )
87+ . then ( doWriteWithCancelPostSync )
5888 . then ( common . mustCall ( ) ) ;
89+
90+ function checkIfFileIsOpen ( fileName ) {
91+ const platform = os . platform ( ) ;
92+ if ( platform === 'linux' || platform === 'darwin' ) {
93+ // Tried other ways like rm/stat, but that didn't work.
94+ cp . exec ( `lsof -p ${ process . pid } ` , common . mustCall ( ( err , value ) => {
95+ if ( err ) {
96+ assert . ifError ( err ) ;
97+ return ;
98+ }
99+ assert . ok ( ! value . toString ( ) . includes ( fileName ) ,
100+ `${ fileName } is still open, but should be closed` ) ;
101+ } ) ) ;
102+ }
103+ }
0 commit comments