File tree Expand file tree Collapse file tree 2 files changed +19
-18
lines changed
changelog_unreleased/misc Expand file tree Collapse file tree 2 files changed +19
-18
lines changed Original file line number Diff line number Diff line change
1
+ #### Avoid closing files multiple times (#17665 by @43081j )
2
+
3
+ When reading a file to infer the interpreter from a shebang, we use the
4
+ ` n-readlines ` library to read the first line in order to get the shebang.
5
+
6
+ This library closes files when it reaches EOF, and we later try close the same
7
+ files again. We now close files only if ` n-readlines ` did not already close
8
+ them.
Original file line number Diff line number Diff line change 1
- import fs from "node:fs" ;
2
1
import readlines from "n-readlines" ;
3
2
4
3
/**
5
4
* @param {string | URL } file
6
5
* @returns {string | undefined }
7
6
*/
8
7
function getInterpreter ( file ) {
9
- let fd ;
10
8
try {
11
- fd = fs . openSync ( file , "r" ) ;
12
- } catch {
13
- /* c8 ignore next */
14
- return ;
15
- }
9
+ const liner = new readlines ( file ) ;
10
+ const firstLineBuffer = liner . next ( ) ;
16
11
17
- try {
18
- const liner = new readlines ( fd ) ;
19
- const firstLine = liner . next ( ) . toString ( "utf8" ) ;
12
+ if ( firstLineBuffer === false ) {
13
+ return ;
14
+ }
15
+
16
+ liner . close ( ) ;
17
+
18
+ const firstLine = firstLineBuffer . toString ( "utf8" ) ;
20
19
21
20
// #!/bin/env node, #!/usr/bin/env node
22
21
const m1 = firstLine . match ( / ^ # ! \/ (?: u s r \/ ) ? b i n \/ e n v \s + ( \S + ) / u) ;
@@ -29,14 +28,8 @@ function getInterpreter(file) {
29
28
if ( m2 ) {
30
29
return m2 [ 1 ] ;
31
30
}
32
- } finally {
33
- try {
34
- // There are some weird cases where paths are missing, causing Jest
35
- // failures. It's unclear what these correspond to in the real world.
36
- fs . closeSync ( fd ) ;
37
- } catch {
38
- // noop
39
- }
31
+ } catch {
32
+ // couldn't open the file
40
33
}
41
34
}
42
35
You can’t perform that action at this time.
0 commit comments