2
2
3
3
const common = require ( '../common' ) ;
4
4
const fs = require ( 'fs' ) ;
5
+ const os = require ( 'os' ) ;
6
+ const cp = require ( 'child_process' ) ;
5
7
const fsPromises = fs . promises ;
6
8
const path = require ( 'path' ) ;
7
9
const tmpdir = require ( '../common/tmpdir' ) ;
@@ -11,7 +13,9 @@ const tmpDir = tmpdir.path;
11
13
tmpdir . refresh ( ) ;
12
14
13
15
const 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' ) ;
15
19
const buffer = Buffer . from ( 'abc' . repeat ( 1000 ) ) ;
16
20
const buffer2 = Buffer . from ( 'xyz' . repeat ( 1000 ) ) ;
17
21
@@ -25,9 +29,33 @@ async function doWriteWithCancel() {
25
29
const controller = new AbortController ( ) ;
26
30
const { signal } = controller ;
27
31
process . nextTick ( ( ) => controller . abort ( ) ) ;
28
- assert . rejects ( fsPromises . writeFile ( otherDest , buffer , { signal } ) , {
32
+ assert . rejects ( fsPromises . writeFile ( otherDest2 , buffer , { signal } ) , {
29
33
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
+ } ) ) ;
31
59
}
32
60
33
61
async function doAppend ( ) {
@@ -55,4 +83,21 @@ doWrite()
55
83
. then ( doAppend )
56
84
. then ( doRead )
57
85
. then ( doReadWithEncoding )
86
+ . then ( doWriteWithCancelPreSync )
87
+ . then ( doWriteWithCancelPostSync )
58
88
. 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