* Waits for a file to be created and populated (removed = false) or removed (removed = true).
(filePath: string, removed = false)
| 29 | * Waits for a file to be created and populated (removed = false) or removed (removed = true). |
| 30 | */ |
| 31 | function waitForFile(filePath: string, removed = false) { |
| 32 | return new Promise<void>((resolve, reject) => { |
| 33 | const check = () => { |
| 34 | const exists = fs.existsSync(filePath); |
| 35 | if (removed) { |
| 36 | return !exists; |
| 37 | } |
| 38 | if (!exists) { |
| 39 | return false; |
| 40 | } |
| 41 | try { |
| 42 | return fs.statSync(filePath).size > 0; |
| 43 | } catch { |
| 44 | return false; |
| 45 | } |
| 46 | }; |
| 47 | |
| 48 | if (check()) { |
| 49 | resolve(); |
| 50 | return; |
| 51 | } |
| 52 | |
| 53 | const timer = setTimeout(() => { |
| 54 | fs.unwatchFile(filePath); |
| 55 | reject( |
| 56 | new Error( |
| 57 | `Timeout: file ${filePath} ${removed ? 'not removed' : 'not found'} within ${FILE_TIMEOUT}ms`, |
| 58 | ), |
| 59 | ); |
| 60 | }, FILE_TIMEOUT); |
| 61 | |
| 62 | fs.watchFile(filePath, {interval: 500}, () => { |
| 63 | if (check()) { |
| 64 | clearTimeout(timer); |
| 65 | fs.unwatchFile(filePath); |
| 66 | resolve(); |
| 67 | } |
| 68 | }); |
| 69 | }); |
| 70 | } |
| 71 | |
| 72 | function delay(ms: number) { |
| 73 | return new Promise<void>(resolve => { |
no test coverage detected