| |
| |
| |
| |
|
|
| import chokidar, { FSWatcher } from "chokidar"; |
| import { basename } from "path"; |
| import { loadPost, removePost, getPostsDirectory } from "../services/postService.js"; |
| import { siteConfig } from "../../shared/config.js"; |
|
|
| let watcher: FSWatcher | null = null; |
|
|
| const isMarkdownFile = (filePath: string): boolean => { |
| return siteConfig.files.markdownExtensionPattern.test(filePath); |
| }; |
|
|
| const createFileEventHandler = ( |
| eventLabel: string, |
| action: (filename: string) => void | Promise<void> |
| ): ((filePath: string) => void) => { |
| return (filePath: string): void => { |
| if (!isMarkdownFile(filePath)) { |
| return; |
| } |
|
|
| const filename = basename(filePath); |
| console.log(`${eventLabel}: ${filename}`); |
| action(filename); |
| }; |
| }; |
|
|
| export const initializeFileWatcher = (): void => { |
| if (watcher) { |
| return; |
| } |
|
|
| const postsDirectory = getPostsDirectory(); |
|
|
| watcher = chokidar.watch(postsDirectory, { |
| persistent: siteConfig.fileWatcher.persistent, |
| ignoreInitial: siteConfig.fileWatcher.ignoreInitial, |
| awaitWriteFinish: { |
| stabilityThreshold: siteConfig.fileWatcher.stabilityThreshold, |
| pollInterval: siteConfig.fileWatcher.pollInterval, |
| }, |
| }); |
|
|
| watcher.on("add", createFileEventHandler(siteConfig.logs.newPostDetected, loadPost)); |
| watcher.on("change", createFileEventHandler(siteConfig.logs.postUpdated, loadPost)); |
| watcher.on("unlink", createFileEventHandler(siteConfig.logs.postDeleted, removePost)); |
|
|
| console.log(siteConfig.logs.watchingDirectory(postsDirectory)); |
| }; |
|
|
| export const stopFileWatcher = async (): Promise<void> => { |
| if (watcher) { |
| await watcher.close(); |
| watcher = null; |
| } |
| }; |