summaryrefslogtreecommitdiff
path: root/cli/js/fs_events.ts
blob: a4deff48a0ed269961232a2f4ff7b9c52cbd484b (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
// Copyright 2019 the Deno authors. All rights reserved. MIT license.
import { sendSync, sendAsync } from "./dispatch_json.ts";
import * as dispatch from "./dispatch.ts";
import { close } from "./files.ts";

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

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

  constructor(paths: string[], options: { recursive: boolean }) {
    const { recursive } = options;
    this.rid = sendSync(dispatch.OP_FS_EVENTS_OPEN, { recursive, paths });
  }

  async next(): Promise<IteratorResult<FsEvent>> {
    return await sendAsync(dispatch.OP_FS_EVENTS_POLL, {
      rid: this.rid
    });
  }

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

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

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