( filePath, options, )
| 52 | * Node.js tail source factory for `useTail`. |
| 53 | */ |
| 54 | export const createNodeTailSource: TailSourceFactory<string> = ( |
| 55 | filePath, |
| 56 | options, |
| 57 | ): TailSource<string> => { |
| 58 | const pollMs = normalizePositiveInteger(options.pollMs, DEFAULT_POLL_MS); |
| 59 | const fromEnd = options.fromEnd; |
| 60 | |
| 61 | let closed = false; |
| 62 | let sleepState: SleepState = { timer: null, resolve: null }; |
| 63 | |
| 64 | const wakeSleep = (): void => { |
| 65 | if (sleepState.timer !== null) { |
| 66 | clearTimeout(sleepState.timer); |
| 67 | } |
| 68 | if (sleepState.resolve) { |
| 69 | sleepState.resolve(); |
| 70 | } |
| 71 | sleepState = { timer: null, resolve: null }; |
| 72 | }; |
| 73 | |
| 74 | const sleep = async (ms: number): Promise<void> => { |
| 75 | if (ms <= 0) return; |
| 76 | |
| 77 | await new Promise<void>((resolve) => { |
| 78 | const timer = setTimeout(() => { |
| 79 | sleepState = { timer: null, resolve: null }; |
| 80 | resolve(); |
| 81 | }, ms); |
| 82 | sleepState = { timer, resolve }; |
| 83 | }); |
| 84 | }; |
| 85 | |
| 86 | async function* iterator(): AsyncGenerator<string> { |
| 87 | let initialized = false; |
| 88 | let offset = 0; |
| 89 | let carry = ""; |
| 90 | let decoder = new StringDecoder("utf8"); |
| 91 | |
| 92 | while (!closed) { |
| 93 | let fileSize: number; |
| 94 | try { |
| 95 | const stats = await stat(filePath); |
| 96 | fileSize = Number(stats.size); |
| 97 | } catch (error) { |
| 98 | if (isNodeErrorWithCode(error) && error.code === "ENOENT") { |
| 99 | await sleep(pollMs); |
| 100 | continue; |
| 101 | } |
| 102 | throw error; |
| 103 | } |
| 104 | |
| 105 | if (!initialized) { |
| 106 | initialized = true; |
| 107 | offset = fromEnd ? fileSize : 0; |
| 108 | } |
| 109 | |
| 110 | if (fileSize < offset) { |
| 111 | // File was truncated/rotated. |
no test coverage detected