File size: 1,629 Bytes
1e92f2d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import { watch } from 'fs'
import { access, constants } from 'fs/promises'
import { dirname } from 'path'

export async function waitForFile(
  path: string,
  timeout: number
): Promise<void> {
  let currentAction = ''
  let timeoutRef
  const timeoutPromise = new Promise<void>((resolve, reject) => {
    timeoutRef = setTimeout(() => {
      reject(
        new Error(`Timed out waiting for file ${path} (${currentAction}))`)
      )
    }, timeout || 60000)
  })
  const elements: string[] = []
  let current = path
  while (true) {
    elements.push(current)
    const parent = dirname(current)
    if (parent === current) {
      break
    }
    current = parent
  }
  elements.reverse()
  try {
    for (const path of elements) {
      const checkAccess = () =>
        access(path, constants.F_OK)
          .then(() => true)
          .catch(() => false)
      if (!(await checkAccess())) {
        let resolveCheckAgain = () => {}
        const watcher = watch(dirname(path), () => {
          resolveCheckAgain()
        })
        currentAction = `waiting for ${path}`
        let checkAgainPromise = new Promise<void>((resolve) => {
          resolveCheckAgain = resolve
        })
        try {
          do {
            await Promise.race([timeoutPromise, checkAgainPromise])
            // eslint-disable-next-line no-loop-func
            checkAgainPromise = new Promise<void>((resolve) => {
              resolveCheckAgain = resolve
            })
          } while (!(await checkAccess()))
        } finally {
          watcher.close()
        }
      }
    }
  } finally {
    clearTimeout(timeoutRef)
  }
}