fs/promises#rm TypeScript Examples

The following examples show how to use fs/promises#rm. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: cache.ts    From cloudmusic-vscode with MIT License 7 votes vote down vote up
static async get(key: string): Promise<LyricCacheItem | void> {
    try {
      const path = resolve(LYRIC_CACHE_DIR, key);
      const data = JSON.parse(
        (await readFile(path)).toString()
      ) as LyricCacheItem;
      // 7 * 24 * 60 * 60 * 1000
      if (Date.now() - data.ctime < 604800000) return data;
      void rm(path, { recursive: true, force: true });
    } catch {}
    return;
  }
Example #2
Source File: server.ts    From cloudmusic-vscode with MIT License 7 votes vote down vote up
static async init(): Promise<void> {
    await rm(ipcBroadcastServerPath, { recursive: true, force: true }).catch(
      () => undefined
    );

    this._server = createServer((socket) => {
      this._sockets.add(socket);

      socket
        .setEncoding("utf8")
        .on("data", (data) => this._broadcast(data))
        .on("close", (/* err */) => {
          socket?.destroy();
          this._sockets.delete(socket);
        })
        .on("error", logError);
    })
      .on("error", logError)
      .listen(ipcBroadcastServerPath);
  }
Example #3
Source File: cache.ts    From cloudmusic-vscode with MIT License 6 votes vote down vote up
static async init(): Promise<void> {
    const names = new Set(
      (await readdir(MUSIC_CACHE_DIR, { withFileTypes: true }))
        .filter((i) => i.isFile())
        .map(({ name }) => name)
    );

    try {
      const list = JSON.parse(
        (await readFile(this._listPath)).toString()
      ) as readonly MusicCacheNode[];

      list
        .filter(({ name }) => names.has(name))
        .reverse()
        .forEach((value) => {
          names.delete(value.name);
          this._addNode(value);
        });
    } catch {}
    void this.store();

    for (const name of names) {
      const path = resolve(MUSIC_CACHE_DIR, name);
      rm(path, { recursive: true, force: true }).catch(logError);
    }
  }
Example #4
Source File: cache.ts    From cloudmusic-vscode with MIT License 6 votes vote down vote up
static clear(): void {
    rm(MUSIC_CACHE_DIR, { recursive: true })
      .catch(() => undefined)
      .then(() => mkdir(MUSIC_CACHE_DIR, { recursive: true }))
      .catch(() => undefined);
    this._cache.clear();
    this._size = 0;
    while (this._list.length) this._list.pop();
    void this.store();
  }
Example #5
Source File: cache.ts    From cloudmusic-vscode with MIT License 6 votes vote down vote up
private static _deleteNode({ key, name }: { key: string; name: string }) {
    const node = this._cache.get(key);
    if (node) {
      this._list.removeNode(node);
      this._cache.delete(key);
      this._size -= node.value.size;
      void rm(resolve(MUSIC_CACHE_DIR, name), { recursive: true, force: true });
    }
  }
Example #6
Source File: index.ts    From cloudmusic-vscode with MIT License 6 votes vote down vote up
(async () => {
  Player.init();
  void IPCServer.init();
  void IPCBroadcastServer.init();

  await mkdir(TMP_DIR).catch(() => undefined);
  await mkdir(CACHE_DIR).catch(() => undefined);
  await mkdir(LYRIC_CACHE_DIR).catch(() => undefined);
  await mkdir(MUSIC_CACHE_DIR).catch(() => undefined);
  await MusicCache.init();

  setInterval(
    () => {
      readdir(TMP_DIR)
        .then((files) => {
          for (const file of files) {
            // Playing || Downloading
            if (file === `${Player.id}` || file === `${Player.next?.id || ""}`)
              continue;
            // Remove unused file
            const path = resolve(TMP_DIR, file);
            rm(path).catch(logError);
            // every tick only delete one file
            return;
          }
          // If no files were deleted, the cache can be considered stable
          // In practice, this is mostly invoked every 4 minutes (two ticks)
          void MusicCache.store();
        })
        .catch(logError);
    },
    // Assume the duration of a song is 3.5 minutes
    // Do the cleanup every 2 minutes (2 * 60 * 1000 = 120000)
    120000
  );
})().catch(logError);
Example #7
Source File: index.spec.ts    From hoprnet with GNU General Public License v3.0 6 votes vote down vote up
describe('hopr core (instance)', async function () {
  it('should be able to start a hopr node instance without crashing', async function () {
    this.timeout(5000)
    log('Clean up data folder from previous attempts')
    await rm(sampleOptions.dataPath, { recursive: true, force: true })

    log('Creating hopr node...')
    const connectorMock = createConnectorMock(peerId)
    const node = new Hopr(peerId, dbMock, connectorMock, sampleOptions as HoprOptions)

    log('Node created with Id', node.getId().toB58String())
    assert(node instanceof Hopr)

    log('Starting node')
    await node.start()

    // Give libp2p some time to initialize
    await setTimeout(1000)

    await assert.doesNotReject(async () => await node.stop())

    log('Clean up data folder')
    await rm(sampleOptions.dataPath, { recursive: true, force: true })
  })
})
Example #8
Source File: cache.ts    From cloudmusic-vscode with MIT License 5 votes vote down vote up
static clear(): void {
    rm(LYRIC_CACHE_DIR, { recursive: true })
      .catch(() => undefined)
      .then(() => mkdir(LYRIC_CACHE_DIR, { recursive: true }))
      .catch(() => undefined);
  }
Example #9
Source File: db.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
async init(initialize: boolean, dbPath: string, forceCreate: boolean = false, environmentId: string) {
    let setEnvironment = false

    log(`using db at ${dbPath}`)
    if (forceCreate) {
      log('force create - wipe old database and create a new')
      await rm(dbPath, { recursive: true, force: true })
      await mkdir(dbPath, { recursive: true })
      setEnvironment = true
    }

    let exists = false

    try {
      exists = !(await stat(dbPath)).isDirectory()
    } catch (err: any) {
      if (err.code === 'ENOENT') {
        exists = false
      } else {
        // Unexpected error, therefore throw it
        throw err
      }
    }

    if (!exists) {
      log('db directory does not exist, creating?:', initialize)
      if (initialize) {
        await mkdir(dbPath, { recursive: true })
        setEnvironment = true
      } else {
        throw new Error('Database does not exist: ' + dbPath)
      }
    }
    this.db = levelup(leveldown(dbPath))

    // Fully initialize database
    await this.db.open()

    log(`namespacing db by native address: ${this.id.toCompressedPubKeyHex()}`)
    if (setEnvironment) {
      log(`setting environment id ${environmentId} to db`)
      await this.setEnvironmentId(environmentId)
    } else {
      const hasEnvironmentKey = await this.verifyEnvironmentId(environmentId)

      if (!hasEnvironmentKey) {
        const storedId = await this.getEnvironmentId()

        throw new Error(`invalid db environment id: ${storedId} (expected: ${environmentId})`)
      }
    }
  }
Example #10
Source File: shell.ts    From command-bot with Apache License 2.0 5 votes vote down vote up
initDatabaseDir = async (dir: string) => {
  dir = await ensureDir(dir)
  await rm(path.join(dir, "LOCK"), {
    // ignore error if the file does not exist
    force: true,
  })
  return dir
}
Example #11
Source File: ipc.ts    From cloudmusic-vscode with MIT License 4 votes vote down vote up
export async function initIPC(context: ExtensionContext): Promise<void> {
  const ipcHandler = (data: IPCServerMsg | NeteaseAPISMsg<NeteaseAPIKey>) => {
    switch (data.t) {
      case IPCApi.netease:
        {
          const req = IPC.requestPool.get(data.channel);
          if (!req) break;
          IPC.requestPool.delete(data.channel);
          if ((data.msg as { err?: true })["err"] === true) req.reject();
          else req.resolve(data.msg);
        }
        break;
      case IPCControl.netease:
        AccountManager.accounts.clear();
        data.profiles.forEach((i) => AccountManager.accounts.set(i.userId, i));
        PlaylistProvider.refresh();
        RadioProvider.refresh();
        AccountViewProvider.account(data.profiles);
        State.downInit(); // 2
        if (State.master) {
          if (!data.cookies.length) IPC.clear();
          void context.secrets.store(COOKIE_KEY, JSON.stringify(data.cookies));
        }
        break;
      case IPCControl.master:
        State.master = !!data.is;
        break;
      case IPCControl.new:
        IPC.new();
        break;
      case IPCControl.retain:
        QueueProvider.new(data.items as PlayTreeItemData[]);
        State.downInit(); // 1
        break;
      case IPCPlayer.end:
        if (!data.fail && State.repeat) IPC.load();
        else void commands.executeCommand("cloudmusic.next");
        break;
      case IPCPlayer.loaded:
        State.loading = false;
        break;
      case IPCPlayer.lyric:
        State.lyric = {
          ...State.lyric,
          ...data.lyric,
        };
        break;
      case IPCPlayer.lyricIndex:
        ButtonManager.buttonLyric(State.lyric.text[data.idx][State.lyric.type]);
        State.lyric.updateIndex?.(data.idx);
        break;
      case IPCPlayer.pause:
        ButtonManager.buttonPlay(false);
        AccountViewProvider.pause();
        break;
      case IPCPlayer.play:
        ButtonManager.buttonPlay(true);
        AccountViewProvider.play();
        break;
      case IPCPlayer.stop:
        ButtonManager.buttonSong();
        ButtonManager.buttonLyric();
        State.lyric = {
          ...State.lyric,
          ...defaultLyric,
        };
        AccountViewProvider.stop();
        break;
      case IPCPlayer.volume:
        ButtonManager.buttonVolume(data.level);
        break;
      case IPCPlayer.next:
        void commands.executeCommand("cloudmusic.next");
        break;
      case IPCPlayer.previous:
        void commands.executeCommand("cloudmusic.previous");
        break;
      case IPCPlayer.speed:
        ButtonManager.buttonSpeed(data.speed);
        break;
      case IPCQueue.fm:
        State.fm = true;
        break;
      case IPCQueue.fmNext:
        State.playItem = QueueItemTreeItem.new({
          ...data.item,
          pid: data.item.al.id,
        });
        break;
      case IPCWasm.load:
        AccountViewProvider.wasmLoad(data.path);
        break;
      case IPCWasm.pause:
        AccountViewProvider.wasmPause();
        break;
      case IPCWasm.play:
        AccountViewProvider.wasmPlay();
        break;
      case IPCWasm.stop:
        AccountViewProvider.wasmStop();
        break;
      case IPCWasm.volume:
        AccountViewProvider.wasmVolume(data.level);
        break;
      case IPCWasm.speed:
        AccountViewProvider.wasmSpeed(data.speed);
        break;
    }
  };

  try {
    const firstTry = await IPC.connect(ipcHandler, ipcBHandler, 0);
    if (firstTry.includes(false)) throw Error;
  } catch {
    State.first = true;
    State.downInit(); // 1
    const version = (context.extension.packageJSON as { version: string })
      .version;
    const log = `err-${version}.log`;
    const logPath = resolve(SETTING_DIR, log);
    const httpProxy =
      workspace.getConfiguration("http").get<string>("proxy") ||
      process.env.HTTPS_PROXY ||
      process.env.HTTP_PROXY;
    const ipcServerPath = resolve(context.extensionPath, "dist", "server.js");
    const conf = CONF();
    spawn(process.execPath, [...process.execArgv, ipcServerPath], {
      detached: true,
      shell: false,
      stdio: ["ignore", "ignore", (await open(logPath, "a")).fd],
      env: {
        ...process.env,
        // eslint-disable-next-line @typescript-eslint/naming-convention
        ...(STRICT_SSL ? {} : { NODE_TLS_REJECT_UNAUTHORIZED: "0" }),
        // eslint-disable-next-line @typescript-eslint/naming-convention
        ...(httpProxy ? { GLOBAL_AGENT_HTTP_PROXY: httpProxy } : {}),
        // eslint-disable-next-line @typescript-eslint/naming-convention
        CM_SETTING_DIR: SETTING_DIR,
        // eslint-disable-next-line @typescript-eslint/naming-convention
        CM_NATIVE_MODULE: NATIVE_MODULE,
        // eslint-disable-next-line @typescript-eslint/naming-convention
        CM_VOLUME: context.globalState.get(VOLUME_KEY, 85).toString(),
        // eslint-disable-next-line @typescript-eslint/naming-convention
        CM_SPEED: context.globalState.get(SPEED_KEY, 1).toString(),
        // eslint-disable-next-line @typescript-eslint/naming-convention
        CM_WASM: State.wasm ? "1" : "0",
        // eslint-disable-next-line @typescript-eslint/naming-convention
        CM_MUSIC_QUALITY: MUSIC_QUALITY(conf).toString(),
        // eslint-disable-next-line @typescript-eslint/naming-convention
        CM_MUSIC_CACHE_SIZE: MUSIC_CACHE_SIZE(conf).toString(),
        // eslint-disable-next-line @typescript-eslint/naming-convention
        CM_HTTPS_API: HTTPS_API(conf) ? "1" : "0",
        // eslint-disable-next-line @typescript-eslint/naming-convention
        CM_FOREIGN: FOREIGN(conf) ? "1" : "0",
      },
    }).unref();
    await IPC.connect(ipcHandler, ipcBHandler);
    readdir(SETTING_DIR, { withFileTypes: true })
      .then((dirents) => {
        for (const dirent of dirents) {
          if (
            dirent.isFile() &&
            dirent.name.startsWith("err") &&
            dirent.name !== log
          )
            rm(resolve(SETTING_DIR, dirent.name), {
              recursive: true,
              force: true,
            }).catch(console.error);
        }
      })
      .catch(console.error);
  }
}
Example #12
Source File: server.ts    From cloudmusic-vscode with MIT License 4 votes vote down vote up
static async init() {
    const [buf] = await Promise.allSettled([
      readFile(RETAIN_FILE),
      rm(ipcServerPath, { recursive: true, force: true }),
    ]);
    if (buf.status === "fulfilled")
      this._retain = JSON.parse(buf.value.toString()) as unknown[];

    this._server = createServer((socket) => {
      if (this._timer) {
        clearTimeout(this._timer);
        this._timer = undefined;
      }
      this._sockets.add(socket);
      this._buffer.set(socket, "");

      socket
        .setEncoding("utf8")
        .on("data", (data) => {
          const buffer = (this._buffer.get(socket) ?? "") + data.toString();

          const msgs = buffer.split(ipcDelimiter);
          this._buffer.set(socket, msgs.pop() ?? "");
          for (const msg of msgs)
            this._handler(
              JSON.parse(msg) as IPCClientMsg | NeteaseAPICMsg<"album">,
              socket
            );
        })
        .on("close", (/* err */) => {
          let isMaster = false;
          {
            const [master] = this._sockets;
            isMaster = master === socket;
          }
          socket?.destroy();
          this._sockets.delete(socket);
          this._buffer.delete(socket);

          if (this._sockets.size) {
            this._setMaster();
            if (isMaster) {
              // Master was gone, the wasm player was destroyed
              // So we need to recreate it on new master
              Player.wasmOpen();
            }
          } else {
            Player.pause();
            this._timer = setTimeout(() => {
              if (this._sockets.size) return;
              this.stop();
              IPCBroadcastServer.stop();
              Promise.allSettled([
                MusicCache.store(),
                rm(TMP_DIR, { recursive: true }),
                writeFile(RETAIN_FILE, JSON.stringify(this._retain)),
              ]).finally(() => process.exit());
            }, 20000);
          }
        })
        .on("error", logError);

      this._setMaster();

      if (this._sockets.size === 1) {
        // retain
        if (!this._first) {
          Player.play();

          this.send(socket, { t: IPCControl.retain, items: this._retain });
          this._retain = [];
        } else this._first = false;
      } else {
        this.sendToMaster({ t: IPCControl.new });
        this.send(socket, {
          t: Player.playing ? IPCPlayer.play : IPCPlayer.pause,
        });
      }
    })
      .on("error", logError)
      .listen(ipcServerPath);
  }