( path: string, timeout: number )
| 3 | import { dirname } from 'path' |
| 4 | |
| 5 | export async function waitForFile( |
| 6 | path: string, |
| 7 | timeout: number |
| 8 | ): Promise<void> { |
| 9 | let currentAction = '' |
| 10 | let timeoutRef |
| 11 | const timeoutPromise = new Promise<void>((resolve, reject) => { |
| 12 | timeoutRef = setTimeout(() => { |
| 13 | reject( |
| 14 | new Error(`Timed out waiting for file ${path} (${currentAction}))`) |
| 15 | ) |
| 16 | }, timeout || 60000) |
| 17 | }) |
| 18 | const elements: string[] = [] |
| 19 | let current = path |
| 20 | while (true) { |
| 21 | elements.push(current) |
| 22 | const parent = dirname(current) |
| 23 | if (parent === current) { |
| 24 | break |
| 25 | } |
| 26 | current = parent |
| 27 | } |
| 28 | elements.reverse() |
| 29 | try { |
| 30 | for (const path of elements) { |
| 31 | const checkAccess = () => |
| 32 | access(path, constants.F_OK) |
| 33 | .then(() => true) |
| 34 | .catch(() => false) |
| 35 | if (!(await checkAccess())) { |
| 36 | let resolveCheckAgain = () => {} |
| 37 | const watcher = watch(dirname(path), () => { |
| 38 | resolveCheckAgain() |
| 39 | }) |
| 40 | currentAction = `waiting for ${path}` |
| 41 | let checkAgainPromise = new Promise<void>((resolve) => { |
| 42 | resolveCheckAgain = resolve |
| 43 | }) |
| 44 | try { |
| 45 | do { |
| 46 | await Promise.race([timeoutPromise, checkAgainPromise]) |
| 47 | // eslint-disable-next-line no-loop-func |
| 48 | checkAgainPromise = new Promise<void>((resolve) => { |
| 49 | resolveCheckAgain = resolve |
| 50 | }) |
| 51 | } while (!(await checkAccess())) |
| 52 | } finally { |
| 53 | watcher.close() |
| 54 | } |
| 55 | } |
| 56 | } |
| 57 | } finally { |
| 58 | clearTimeout(timeoutRef) |
| 59 | } |
| 60 | } |
no test coverage detected