| 11 | * File written by the bootloader containing some process information. |
| 12 | */ |
| 13 | export class CallbackFile<T> implements IDisposable { |
| 14 | private static readonly pollInterval = 200; |
| 15 | |
| 16 | /** |
| 17 | * Path of the callback file. |
| 18 | */ |
| 19 | public readonly path = path.join( |
| 20 | tmpdir(), |
| 21 | `node-debug-callback-${randomBytes(8).toString('hex')}`, |
| 22 | ); |
| 23 | |
| 24 | private disposed = false; |
| 25 | private readPromise?: Promise<T | undefined>; |
| 26 | |
| 27 | /** |
| 28 | * Reads the file, returnings its contants after they're written, or returns |
| 29 | * undefined if the file was disposed of before the read completed. |
| 30 | */ |
| 31 | public read(pollInterval = CallbackFile.pollInterval) { |
| 32 | if (this.readPromise) { |
| 33 | return this.readPromise; |
| 34 | } |
| 35 | |
| 36 | this.readPromise = new Promise<T | undefined>((resolve, reject) => { |
| 37 | const interval = setInterval(() => { |
| 38 | if (this.disposed) { |
| 39 | clearInterval(interval); |
| 40 | resolve(undefined); |
| 41 | return; |
| 42 | } |
| 43 | |
| 44 | if (!existsSync(this.path)) { |
| 45 | return; |
| 46 | } |
| 47 | |
| 48 | try { |
| 49 | resolve(JSON.parse(readFileSync(this.path, 'utf-8'))); |
| 50 | } catch (e) { |
| 51 | reject(e); |
| 52 | } finally { |
| 53 | this.dispose(); |
| 54 | } |
| 55 | |
| 56 | clearInterval(interval); |
| 57 | }, pollInterval); |
| 58 | }); |
| 59 | |
| 60 | return this.readPromise; |
| 61 | } |
| 62 | |
| 63 | /** |
| 64 | * Diposes of the callback file. |
| 65 | */ |
| 66 | public dispose() { |
| 67 | if (this.disposed) { |
| 68 | return; |
| 69 | } |
| 70 | |