@@ -3,45 +3,19 @@ import { promises as fsPromises } from "fs";
3
3
4
4
const { readFile } = fsPromises ;
5
5
6
- type callbacks = { resolve : Function ; reject : Function } ;
7
- type FileStatus = {
8
- contents : string ;
9
- isReading : boolean ;
10
- requestQueue : callbacks [ ] ;
11
- } ;
12
-
13
- const fileStatusHash : { [ key : string ] : FileStatus } = { } ;
6
+ const filePromisesHash : { [ key : string ] : Promise < string > } = { } ;
14
7
15
- export const slurpFile = ( path : string ) =>
16
- new Promise < string > ( ( resolve , reject ) => {
17
- if ( ! fileStatusHash [ path ] ) {
18
- // File not read yet, set file isReading to true and read file.
19
- fileStatusHash [ path ] = { isReading : true , contents : "" , requestQueue : [ ] } ;
20
- fileStatusHash [ path ] . requestQueue . push ( { resolve, reject } ) ;
8
+ export const slurpFile = ( path : string ) => {
9
+ if ( ! filePromisesHash [ path ] ) {
10
+ filePromisesHash [ path ] = new Promise ( ( resolve , reject ) => {
21
11
readFile ( path , "utf8" )
22
12
. then ( ( data ) => {
23
- // File read successful
24
- fileStatusHash [ path ] . isReading = false ;
25
- fileStatusHash [ path ] . contents = data ;
26
- const { requestQueue } = fileStatusHash [ path ] ;
27
- while ( requestQueue . length ) {
28
- const { resolve } = requestQueue . pop ( ) ! ;
29
- resolve ( data ) ;
30
- }
13
+ resolve ( data ) ;
31
14
} )
32
15
. catch ( ( err ) => {
33
- // File read failed;
34
- fileStatusHash [ path ] . isReading = false ;
35
- const { requestQueue } = fileStatusHash [ path ] ;
36
- while ( requestQueue . length ) {
37
- const { reject } = requestQueue . pop ( ) ! ;
38
- reject ( err ) ;
39
- }
16
+ reject ( err ) ;
40
17
} ) ;
41
- } else if ( fileStatusHash [ path ] . isReading ) {
42
- // File currently being read. Add callbacks to the request queue.
43
- fileStatusHash [ path ] . requestQueue . push ( { resolve, reject } ) ;
44
- } else {
45
- resolve ( fileStatusHash [ path ] . contents ) ;
46
- }
47
- } ) ;
18
+ } ) ;
19
+ }
20
+ return filePromisesHash [ path ] ;
21
+ } ;
0 commit comments