Skip to content

Instantly share code, notes, and snippets.

@nekomimi-daimao
Last active January 7, 2025 13:48
Show Gist options
  • Save nekomimi-daimao/cdd2205b048b6b557fcefd178151cb85 to your computer and use it in GitHub Desktop.
Save nekomimi-daimao/cdd2205b048b6b557fcefd178151cb85 to your computer and use it in GitHub Desktop.
引数のディレクトリを監視し、一定時間操作がなかったら処理を行うdeno
// deno run --allow-read --allow-run dirWatcher.ts /absolute/path/watch/
const targetEventKind = ["create", "modify", "rename", "remove"];
// 操作が止まったと判断する時間
const delayMsec = 3000;
let promise: Promise<any> | undefined;
let resolve;
let timeoutId;
const targetDir = Deno.args[0];
console.log(targetDir);
for await (const fsEvent of Deno.watchFs(targetDir)) {
if (!targetEventKind.includes(fsEvent.kind)) {
continue;
}
if (!resolve) {
const withResolvers = Promise.withResolvers();
promise = withResolvers.promise;
resolve = withResolvers.resolve;
// fire and forget
run().catch();
}
if (resolve) {
clearTimeout(timeoutId);
timeoutId = setTimeout(resolve, delayMsec);
}
}
async function run() {
if (!promise) {
return;
}
await promise;
promise = undefined;
resolve = undefined;
await doWhat();
}
async function doWhat() {
// やりたい処理をここに書く
console.log("do what you want");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment