summaryrefslogtreecommitdiff
path: root/cli/js/ops/fs_events.ts
blob: ffe19b4d799f19b627306b656ae929809bc16e12 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
// Copyright 2018-2020 the Deno authors. All rights reserved. MIT license.

import { sendSync, sendAsync } from "./dispatch_json.ts";
import { close } from "./resources.ts";

export interface FsEvent {
  kind: "any" | "access" | "create" | "modify" | "remove";
  paths: string[];
}

interface FsWatcherOptions {
  recursive: boolean;
}

class FsWatcher implements AsyncIterableIterator<FsEvent> {
  readonly rid: number;

  constructor(paths: string[], options: FsWatcherOptions) {
    const { recursive } = options;
    this.rid = sendSync("op_fs_events_open", { recursive, paths });
  }

  next(): Promise<IteratorResult<FsEvent>> {
    return sendAsync("op_fs_events_poll", {
      rid: this.rid,
    });
  }

  return(value?: FsEvent): Promise<IteratorResult<FsEvent>> {
    close(this.rid);
    return Promise.resolve({ value, done: true });
  }

  [Symbol.asyncIterator](): AsyncIterableIterator<FsEvent> {
    return this;
  }
}

export function watchFs(
  paths: string | string[],
  options: FsWatcherOptions = { recursive: true },
): AsyncIterableIterator<FsEvent> {
  return new FsWatcher(Array.isArray(paths) ? paths : [paths], options);
}