(filePath: string)
| 6 | import * as fileUtils from '../utils/fileUtils'; |
| 7 | |
| 8 | function readAndWatchFile(filePath: string) { |
| 9 | filePath = fileUtils.resolveFilePath(filePath); |
| 10 | |
| 11 | let fileSize = 0; |
| 12 | let isWatching = false; |
| 13 | const abortController = new AbortController(); |
| 14 | |
| 15 | const readInitialContent = () => { |
| 16 | const fileStream = fs.createReadStream(filePath, { encoding: 'utf8', start: 0 }); |
| 17 | |
| 18 | fileStream.on('data', chunk => { |
| 19 | process.stdout.write(chunk); |
| 20 | }); |
| 21 | |
| 22 | fileStream.on('end', () => { |
| 23 | fileSize = fs.statSync(filePath).size; |
| 24 | |
| 25 | if (!isWatching) { |
| 26 | startWatching(); |
| 27 | } |
| 28 | }); |
| 29 | }; |
| 30 | |
| 31 | const startWatching = () => { |
| 32 | isWatching = true; |
| 33 | fs.watch(filePath, { signal: abortController.signal }, eventType => { |
| 34 | if (eventType === 'change') { |
| 35 | const newFileSize = fs.statSync(filePath).size; |
| 36 | if (newFileSize > fileSize) { |
| 37 | const readStream = fs.createReadStream(filePath, { encoding: 'utf8', start: fileSize }); |
| 38 | readStream.on('data', chunk => { |
| 39 | process.stdout.write(chunk); |
| 40 | }); |
| 41 | fileSize = newFileSize; |
| 42 | } |
| 43 | } else if (eventType === 'rename') { |
| 44 | isWatching = false; |
| 45 | if (fs.existsSync(filePath)) { |
| 46 | // When files is written, sometimes the first reported event |
| 47 | // occurs when the write is incomplete, so verifying the file exists |
| 48 | // before reading and restarting the watch |
| 49 | readInitialContent(); |
| 50 | } |
| 51 | } |
| 52 | }); |
| 53 | }; |
| 54 | |
| 55 | readInitialContent(); |
| 56 | |
| 57 | // Liten for (Ctrl+D) to exit as otherwise it would not do anything |
| 58 | process.stdin.on('end', () => { |
| 59 | abortController.abort(); |
| 60 | }); |
| 61 | |
| 62 | // Keep the process running |
| 63 | process.stdin.resume(); |
| 64 | } |
| 65 |
no test coverage detected