fs#readdir TypeScript Examples

The following examples show how to use fs#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: ActionManager.ts    From ts-discord-bot-boilerplate with MIT License 6 votes vote down vote up
/**
     * Parses files into commands from the configured command path.
     * @param {BotClient} client The original client, for access to the configuration.
     * @returns {Collection<string, Command>} A dictionary of every command in a [name, object] pair.
     */
    public initializeCommands(client: BotClient): void {
        const { commands } = client.settings.paths;

        readdir(commands, (err, files) => {
            if (err) Logger.error(err);

            files.forEach(cmd => {
                if (statSync(join(commands, cmd)).isDirectory()) {
                    this.initializeCommands(client);
                } else {
                    const Command: any = require(join(
                        __dirname,
                        '../../',
                        `${commands}/${cmd.replace('ts', 'js')}`
                    )).default;
                    const command = new Command(client);

                    this.commands.set(command.conf.name, command);
                }
            });
        });
    }
Example #2
Source File: ActionManager.ts    From ts-discord-bot-boilerplate with MIT License 6 votes vote down vote up
/**
     * Initializes every event from the configured event path.
     * @param {BotClient} client The original client, for access to the configuration.
     */
    public initializeEvents(client: BotClient): void {
        const { events } = client.settings.paths;

        readdir(events, (err, files) => {
            if (err) Logger.error(err);

            files.forEach(evt => {
                const Event: any = require(join(
                    __dirname,
                    '../../',
                    `${events}/${evt.replace('ts', 'js')}`
                )).default;

                const event = new Event(client);
                const eventName = evt.split('.')[0];

                client.on(
                    eventName.charAt(0).toLowerCase() + eventName.slice(1),
                    (...args: string[]) => event.run(args)
                );
            });
        });
    }
Example #3
Source File: FileExtractor.ts    From Bridge with GNU General Public License v3.0 6 votes vote down vote up
/**
   * Extract the chart from `this.sourceFolder`. (assumes there is exactly one archive file in that folder)
   */
  beginExtract() {
    setTimeout(this.cancelable(() => {
      readdir(this.sourceFolder, (err, files) => {
        if (err) {
          this.callbacks.error(extractErrors.readError(err), () => this.beginExtract())
        } else if (files.length == 0) {
          this.callbacks.error(extractErrors.emptyError(), () => this.beginExtract())
        } else {
          this.callbacks.start(files[0])
          this.extract(join(this.sourceFolder, files[0]), extname(files[0]) == '.rar')
        }
      })
    }), 100) // Wait for filesystem to process downloaded file
  }
Example #4
Source File: fs.ts    From devoirs with MIT License 6 votes vote down vote up
export function readDirectory(path: PathLike): Promise<Dirent[]> {
  return new Promise<Dirent[]>((resolve, reject) => {
    readdir(
      path,
      { withFileTypes: true },
      (error: Error | null, dirents: Dirent[]) => {
        if (error) {
          return reject(error);
        }

        resolve(dirents);
      }
    );
  });
}
Example #5
Source File: variableResolver.ts    From vscode-openscad with GNU General Public License v3.0 5 votes vote down vote up
// Evaluate version number in format '${#}'
    private async getVersionNumber(
        pattern: string,
        resource: vscode.Uri
    ): Promise<number> {
        // No version number in string: return -1
        if (!pattern.match(VariableResolver.VERSION_FORMAT)) return -1;

        // Replace the number placeholder with a regex number capture pattern
        // Regexp is case insensitive if OS is Windows
        const patternAsRegexp = new RegExp(
            escapeStringRegexp(path.basename(pattern)).replace(
                '\\$\\{#\\}',
                '([1-9][0-9]*)'
            ),
            this._isWindows ? 'i' : ''
        );

        // Get file directory
        const fileDir = path.isAbsolute(pattern)
            ? path.dirname(pattern) // Already absolute path
            : path.dirname(path.join(path.dirname(resource.fsPath), pattern)); // Get path of resource ('pattern' may contain a directory)

        // Make export directory if it doesn't exist
        if (!existsSync(fileDir)) mkdirSync(fileDir);

        // Read all files in directory
        const versionNum: number = await new Promise((resolve, reject) => {
            readdir(fileDir, (err, files) => {
                // Error; Return -2 (dir read error)
                if (err) {
                    if (DEBUG) console.error(err);
                    reject(-2); // File read error
                }

                // Get all the files that match the pattern (with different version numbers)
                const lastVersion = files.reduce(
                    (maxVer: number, file: string) => {
                        // Get pattern matches of file
                        const matched = patternAsRegexp.exec(file);
                        // If there's a match, return whichever version is greater
                        return matched
                            ? Math.max(maxVer, Number(matched[1]))
                            : maxVer;
                    },
                    0
                );

                // if (DEBUG) console.log(`Last version: ${lastVersion}`); // DEBUG

                resolve(lastVersion);
            });
        });

        // if (DEBUG) console.log(`Version num: ${versionNum}`);   // DEBUG

        if (versionNum < 0) return versionNum;
        // Error; return as-is
        else return versionNum + 1; // Return next version

        // Consider adding case for MAX_SAFE_NUMBER (despite it's unlikeliness)
    }
Example #6
Source File: Client.ts    From Pterodactyl-Discord-Bot with MIT License 5 votes vote down vote up
readAsyncDir = promisify(readdir)
Example #7
Source File: Mail.ts    From ModMail with MIT License 5 votes vote down vote up
constructor(private readonly token: string) {
		super();
		this.token = token;
		this.closingThreads = false;
		this.bot = new Client(this.token, {
			disableEvents: {
				TYPING_START: true
			},
			restMode: true,
			allowedMentions: {
				roles: true,
				users: true,
				everyone: false
			},
			defaultImageFormat: 'png'
		});
		this.commands = new Map<string, Command>();
		this.aliases = new Map<string, string>();

		this.utils = new UtilsManager(this);
		this.db = Mongo.getDatabase(this);

		readdir(join(__dirname, '..', '..', 'events'), async (error, files) => {
			if (error) return console.error(error);
			console.log(`[Event Handler] Loading a total of ${files.length} files.`);

			files.forEach(async (file) => {
				if (!file.endsWith('.js') || file.endsWith('.map')) return;
				let event = await import(`${join(__dirname, '..', '..', 'events')}/${file}`);
				const name = file.split('.')[0];
				console.log(`[Event Handler] Loading event ${name}.`);

				if ((event).default instanceof Function) {
					event = Object.assign(event.default, event);
					delete event.default;
				}

				try {
					this.bot.on(name, event.bind(null, this));
				} catch (e) {
					console.error(`[Event Handler] ${e}`);
				} finally {
					delete require.cache[join(__dirname, '..', '..', 'events')];
				}
			});
		});

		readdir(join(__dirname, '..', '..', 'commands'), (error, files) => {
			if (error) console.error(error);
			console.log(`[Command Handler] Loading a total of ${files.length} files.`);

			files.forEach(async (file) => {
				if (!file.endsWith('.js') || file.endsWith('.map')) return;
				try {
					let props: Command = await import(`${join(__dirname, '..', '..', 'commands')}/${file}`);

					// eslint-disable-next-line @typescript-eslint/no-explicit-any
					if ((props as any).default instanceof Command) {
						// eslint-disable-next-line @typescript-eslint/no-explicit-any
						props = Object.assign((props as any).default, props);
						// eslint-disable-next-line @typescript-eslint/no-explicit-any
						delete (props as any).default;
					}

					console.log(`[Command Handler] Loading command ${props.name}.`);

					this.commands.set(props.name, props);
					props.options.aliases.forEach((alias) => {
						this.aliases.set(alias, props.name);
					});
				} catch (e) {
					console.warn(`[Command Handler] Command ${file} failed to load.\nStack Trace: ${e.stack.split('\n', 5).join('\n')}`);
				}
			});
		});
	}
Example #8
Source File: sort-words.ts    From programmer-fa with MIT License 5 votes vote down vote up
readdirPromisified = promisify(readdir)
Example #9
Source File: prepareAppFolder.ts    From engine with MIT License 5 votes vote down vote up
pReaddir = promisify(readdir)
Example #10
Source File: DirectoryUtils.ts    From discord-bot with MIT License 5 votes vote down vote up
static readDirectory = promisify(readdir);
Example #11
Source File: create-rss.ts    From blog with GNU General Public License v3.0 5 votes vote down vote up
readDirAsync = promisify(readdir)
Example #12
Source File: posts.ts    From blog with GNU General Public License v3.0 5 votes vote down vote up
readDirAsync = promisify(readdir)