fs/promises#readdir TypeScript Examples

The following examples show how to use fs/promises#readdir. 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: voiceHandler.ts    From CSZ-Bot with MIT License 6 votes vote down vote up
export async function connectAndPlaySaufen(context: BotContext, filename?: string) {
    const wois = context.voiceChannels.haupt_woischat;
    if (wois.members.size === 0) {
        return;
    }

    const files = await readdir(soundDir);

    const fileToPlay = filename ?? files[Math.floor(Math.random() * files.length)];
    const file = path.resolve(soundDir, fileToPlay);
    try {
        const duration = (await gad.getAudioDurationInSeconds(file)) * 1000;
        await playSaufen(file, duration);
        const connection = await connectToHauptwois(wois);
        connection.subscribe(player);

        await setTimeout(duration);
        connection.disconnect();
    }
    catch(err) {
        logger.error("Could not play saufen", err);
    }
}
Example #2
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 #3
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 #4
Source File: [second].tsx    From core with GNU Affero General Public License v3.0 6 votes vote down vote up
export async function getStaticProps () {
	const docs = await Promise.all((await readdir(docsDir)).map(async el => {
		const isDir = (await lstat(join(docsDir, el))).isDirectory()
		if(!isDir) {
			return {
				name: el.split('.').slice(0, -1).join('.'),
				text: (await readFile(join(docsDir, el))).toString()
			}
		}
		else {
			return {
				name: el,
				list: await Promise.all((await readdir(join(docsDir, el))).map(async e => {
					return {
						name: e.split('.').slice(0, -1).join('.'),
						text: (await readFile(join(docsDir, el, e))).toString()
					}
				}))
			}
		}
		
	}))

	return {
		props: { docs }
	}
}
Example #5
Source File: generate.ts    From iuliia-js with MIT License 6 votes vote down vote up
async function generate() {
    const validator = await createValidator();
    const jsonFiles = (await readdir(INPUT_DIR)).filter((file) => file.endsWith(".json"));

    for (const file of jsonFiles) {
        const inputFile = join(INPUT_DIR, file);
        const outputFile = join(OUTPUT_DIR, basename(file, ".json") + ".ts");
        console.log(`Writing file: ${inputFile}`);
        const output = await jsonToTS(inputFile, validator);
        await writeFile(outputFile, output, "utf8");
    }

    console.log(`Writing file: ${DEFINITIONS_FILE}`);
    const moduleNames = jsonFiles.map((file) => basename(file, ".json"));
    const definitions = createDefinitions(moduleNames);
    await writeFile(DEFINITIONS_FILE, definitions, "utf8");
}
Example #6
Source File: sapio.ts    From sapio-studio with Mozilla Public License 2.0 6 votes vote down vote up
async list_compiled_contracts(): Promise<string[]> {
        const file = path.join(
            app.getPath('userData'),
            'workspaces',
            this.name,
            'compiled_contracts'
        );
        const contracts = await readdir(file, { encoding: 'ascii' });
        return contracts;
    }
Example #7
Source File: saufen.ts    From CSZ-Bot with MIT License 5 votes vote down vote up
async handleInteraction(command: CommandInteraction<CacheType>, client: Client<boolean>, context: BotContext): Promise<void> {
        const subCommand = command.options.getSubcommand() as SubCommand;
        const reply = () => command.reply("WOCHENENDE!! SAUFEN!! GEIL");

        switch (subCommand) {
            case "los": {
                await Promise.all([
                    connectAndPlaySaufen(context),
                    reply()
                ]);
                return;
            }
            case "select": {
                const toPlay = command.options.getString("sound", true);
                await Promise.all([
                    connectAndPlaySaufen(context, toPlay),
                    reply()
                ]);
                return;
            }
            case "add": {
                const soundUrl = new URL(command.options.getString("sound", true));
                const targetPath = path.resolve(soundDir, path.basename(soundUrl.pathname));
                const fileStream = createWriteStream(targetPath);
                const res = await fetch(soundUrl, {
                    method: "GET"
                });
                const savePromise = new Promise((resolve, reject) => {
                    res.body.pipe(fileStream);
                    res.body.on("error", reject);
                    fileStream.on("finish", resolve);
                });
                await Promise.all([
                    savePromise,
                    command.reply("Jo, habs eingefügt")
                ]);
                return;
            }
            case "list": {
                const files = await readdir(soundDir, { withFileTypes: true});
                await command.reply(files.map(f => f.name).join("\n- "));
                return;
            }
            default:
                return assertNever(subCommand);
        }
    }
Example #8
Source File: local.ts    From cloudmusic-vscode with MIT License 5 votes vote down vote up
async getChildren(
    element?: LocalLibraryTreeItem
  ): Promise<(LocalFileTreeItem | LocalLibraryTreeItem)[]> {
    if (!element)
      return [MUSIC_CACHE_DIR, ...LocalProvider.folders].map(
        (folder) => new LocalLibraryTreeItem(folder)
      );

    const action = LocalProvider._actions.get(element);
    LocalProvider._actions.delete(element);

    let items: LocalFileTreeItem[] = [];
    if (LocalProvider._files.has(element)) {
      items = LocalProvider._files.get(element) ?? [];
      action?.resolve(items.map(({ data }) => data));
      return items;
    }

    const folders: string[] = [element.label];
    try {
      for (let idx = 0; idx < folders.length; ++idx) {
        const folder = folders[idx];
        const dirents = await readdir(folder, { withFileTypes: true });
        const paths: string[] = [];

        for (const dirent of dirents) {
          if (dirent.isFile()) paths.push(dirent.name);
          else if (dirent.isDirectory())
            folders.push(resolve(folder, dirent.name));
        }

        const treeitems = (
          await Promise.all(
            paths.map(async (filename) => {
              const id = resolve(folder, filename);
              const mime = await fileTypeFromFile(id);
              return { filename, id, ...mime };
            })
          )
        )
          .filter(({ mime }) => mime && supportedType.includes(mime))
          .map((item) => LocalFileTreeItem.new(item));
        items.push(...treeitems);
      }
    } catch {}
    LocalProvider._files.set(element, items);

    action?.resolve(items.map(({ data }) => data));
    return items;
  }
Example #9
Source File: slimDeployments.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
main: DeployFunction = async function (hre: HardhatRuntimeEnvironment) {
  const basePath = join(
    __dirname,
    '..',
    'deployments',
    hre.environment,
    hre.network.name === 'hardhat' ? 'localhost' : hre.network.name
  )

  let contracts: string[]

  try {
    contracts = (await readdir(basePath)).filter((filename: string) => filename.endsWith('.json'))
  } catch (err) {
    // Ignore missing deployments in unit tests
    if (hre.network.name === 'hardhat' && err.code === 'ENOENT') {
      return
    }

    throw err
  }

  for (const contract of contracts) {
    const filePath = join(basePath, contract)
    const data = require(filePath)
    const contractName = contract.replace('.json', '')
    const compilerData =
      (await hre.artifacts.getBuildInfo(`contracts/${contractName}.sol:${contractName}`)) ?? data.compilerData
    // sometimes not all contracts are deployed, depends on the deployment scripts
    if (!compilerData) continue
    const slimmed = {
      address: data.address,
      transactionHash: data.transactionHash,
      blockNumber: data.receipt ? data.receipt.blockNumber : data.blockNumber,
      metadata: {
        solcVersion: compilerData.solcVersion,
        input: compilerData.input
      },
      abi: data.abi
    }

    await writeFile(filePath, JSON.stringify(slimmed, null, 2))
  }
}
Example #10
Source File: faucet.ts    From hoprnet with GNU General Public License v3.0 5 votes vote down vote up
/**
 * Reads the identity files from the given directory, decrypts
 * them and returns their Ethereum addresses
 * @param directory directory to look for identity files
 * @param password password to decrypt identity files
 * @param prefix only take identities with given prefix
 * @returns the identities' Ethereum addresses
 */
async function getIdentities(directory: string, password: string, prefix?: string): Promise<string[]> {
  let fileNames: string[]
  try {
    fileNames = await readdir(directory)
  } catch (err) {
    console.log(err)
    return []
  }

  const identityFiles: string[] = []
  for (const fileName of fileNames) {
    if ((prefix == null || fileName.startsWith(prefix)) && fileName.endsWith('.id')) {
      identityFiles.push(fileName)
    }
  }

  console.log(`identityFiles`, identityFiles)
  const identites: string[] = []
  for (const identityFile of identityFiles) {
    let file: Uint8Array
    const path = join(directory, identityFile)
    try {
      file = await readFile(path)
    } catch (err) {
      console.log(`Could not access ${path}.`, err)
      continue
    }

    const decoded = await deserializeKeyPair(file, password, true)

    if (decoded.success) {
      identites.push(PublicKey.fromPeerId(decoded.identity).toAddress().toHex())
    } else {
      console.log(`Could not decrypt private key from file ${file} using "${password}" as password (without ")`)
    }
  }

  return identites
}
Example #11
Source File: fetch-api.ts    From mtcute with GNU Lesser General Public License v3.0 5 votes vote down vote up
async function updatePackageVersion(
    rl: readline.Interface,
    currentLayer: number
) {
    const packageJson = JSON.parse(await readFile(PACKAGE_JSON_FILE, 'utf8'))
    const version: string = packageJson.version
    let [major, minor] = version.split('.').map((i) => parseInt(i))

    if (major === currentLayer) {
        console.log('Current version: %s. Bump minor version?', version)
        const res = await input(rl, '[Y/n] > ')

        if (res.trim().toLowerCase() === 'n') {
            return
        }
    } else {
        major = currentLayer
        minor = 0
    }

    console.log('Updating package version...')
    const versionStr = `${major}.${minor}.0`
    packageJson.version = versionStr
    await writeFile(PACKAGE_JSON_FILE, JSON.stringify(packageJson, null, 4))

    console.log('Updating dependant packages...')

    for (const dir of await readdir(PACKAGES_DIR, { withFileTypes: true })) {
        if (!dir.isDirectory()) continue

        const pkgFile = join(PACKAGES_DIR, dir.name, 'package.json')

        let pkg
        try {
            pkg = JSON.parse(await readFile(pkgFile, 'utf8'))
        } catch (e: any) {
            if (e.code === 'ENOENT') continue
            throw e
        }

        if (pkg.dependencies && '@mtcute/tl' in pkg.dependencies) {
            pkg.dependencies['@mtcute/tl'] = 'workspace:' + versionStr
        }

        if (pkg.devDependencies && '@mtcute/tl' in pkg.devDependencies) {
            pkg.devDependencies['@mtcute/tl'] = 'workspace:' + versionStr
        }

        await writeFile(pkgFile, JSON.stringify(pkg, null, 4) + '\n')
    }

    // because i am fucking dumb and have adhd and always forget it lol
    console.log(
        'Done! Please make sure packages compile before committing and pushing'
    )
}
Example #12
Source File: sapio.ts    From sapio-studio with Mozilla Public License 2.0 5 votes vote down vote up
static async list_all(): Promise<string[]> {
        const file = path.join(app.getPath('userData'), 'workspaces');
        return readdir(file, { encoding: 'ascii' });
    }
Example #13
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);
  }
}