fs#readdirSync TypeScript Examples

The following examples show how to use fs#readdirSync. 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: utils.ts    From h1z1-server with GNU General Public License v3.0 7 votes vote down vote up
removeCacheFullDir = function (directoryPath: string): void {
  const files = readdirSync(directoryPath); // need to be sync
  for (const file of files) {
    if (!file.includes(".")) {
      // if it's a folder ( this feature isn't tested but should work well )
      removeCacheFullDir(`${directoryPath}/${file}`);
    }
    if (file.substring(file.length - 3) === ".js") {
      delete require.cache[normalize(`${directoryPath}/${file}`)];
    }
  }
}
Example #2
Source File: fs.ts    From playwright-fluent with MIT License 6 votes vote down vote up
getFilesInDirectory = (
  path: PathLike,
  fileFilter?: (path: string) => boolean,
): string[] =>
  readdirSync(path)
    .map((name) => join(path.toString(), name))
    .filter(isFile)
    .filter(ignoreNodeModule)
    .filter(ignoreDotDir)
    .filter(fileFilter || (() => true))
Example #3
Source File: hardhat.config.ts    From balancer-v2-monorepo with GNU General Public License v3.0 6 votes vote down vote up
task('extract-artifacts', `Extract contract artifacts from their build-info`)
  .addOptionalParam('id', 'Specific task ID')
  .setAction(async (args: { id?: string; verbose?: boolean }) => {
    Logger.setDefaults(false, args.verbose || false);

    if (args.id) {
      const task = new Task(args.id, TaskMode.READ_ONLY);
      extractArtifact(task);
    } else {
      const taskDirectory = path.resolve(__dirname, './tasks');

      for (const taskID of readdirSync(taskDirectory)) {
        const task = new Task(taskID, TaskMode.READ_ONLY);
        extractArtifact(task);
      }
    }
  });
Example #4
Source File: migrate.ts    From dyngoose with ISC License 6 votes vote down vote up
export default async function migrateTables(input: MigrateTablesInput): Promise<void> {
  const tableFiles = readdirSync(input.tablesDirectory)
  const tables: Array<typeof Table> = []
  const log = input.log == null ? console.log : input.log
  const prefix = input.tableNamePrefix == null ? '' : input.tableNamePrefix
  const suffix = input.tableNameSuffix == null ? '' : input.tableNameSuffix
  log('Running Dyngoose migration utility…')

  for (const file of tableFiles) {
    if (file.endsWith(input.tableFileSuffix)) {
      const tableFile = join(input.tablesDirectory, file)
      const tableFileExports = require(tableFile)

      for (const exportedProperty of _.values(tableFileExports)) {
        if (isDyngooseTableClass(exportedProperty)) {
          tables.push(exportedProperty)
        }
      }
    }
  }

  for (const SomeTable of tables) {
    SomeTable.schema.options.name = `${prefix}${SomeTable.schema.name}${suffix}`
    log(`Migrating ${SomeTable.schema.name}`)
    await SomeTable.migrateTable()
  }
}
Example #5
Source File: add-js-extensions.ts    From blake3 with MIT License 6 votes vote down vote up
function processDir(dir: string): void {
  const entries = readdirSync(dir);
  for (const entry of entries) {
    const path = join(dir, entry);
    if (path.endsWith('.js')) {
      processFile(path);
    } else if (statSync(path).isDirectory()) {
      processDir(path);
    }
  }
}
Example #6
Source File: cpGHPages.ts    From fzstd with MIT License 6 votes vote down vote up
git.log({
  from: 'HEAD~1',
  to: 'HEAD'
}).then(async log => {
  const hash = log.latest.hash.slice(0, 7);
  await git.checkout('gh-pages');
  for (const f of readdirSync(to('.'))) {
    if (statSync(f).isFile())
      unlinkSync(to(f));
  }
  const files = readdirSync(to('dist'))
  for (const f of files) {
    copyFileSync(to('dist', f), to(f));
  }
  await git.add(files);
  await git.commit('Build demo from ' + hash);
  await git.checkout('master');
});
Example #7
Source File: expandedPreviewer.ts    From cli with Apache License 2.0 6 votes vote down vote up
private deleteOldestPreviews() {
    const getFilePath = (fileDirent: Dirent) =>
      join(ExpandedPreviewer.previewDirectory, fileDirent.name);

    const getEpochFromSnapshotDir = (dir: Dirent): number =>
      parseInt(dir.name.match(/(?<=-)\d+$/)?.[0] ?? '0');

    const allFiles = readdirSync(ExpandedPreviewer.previewDirectory, {
      withFileTypes: true,
    });
    const dirs = allFiles
      .filter((potentialDir) => potentialDir.isDirectory())
      .sort(
        (dirA, dirB) =>
          getEpochFromSnapshotDir(dirA) - getEpochFromSnapshotDir(dirB)
      );

    while (dirs.length >= ExpandedPreviewer.previewHistorySize) {
      rmSync(getFilePath(dirs.shift()!), {
        recursive: true,
        force: true,
      });
    }
  }
Example #8
Source File: patch.ts    From graphql-typed-document-node with MIT License 6 votes vote down vote up
export async function getAvailablePatches() {
  const baseDir = join(__dirname, './patches/');
  const files = readdirSync(baseDir).filter(d => extname(d) === '.patch');

  return {
    baseDir,
    availablePatches: files.map(fileName => {
      const cleanName = basename(fileName, extname(fileName));
      const parts = cleanName.split('+');
      const versionRange = parts.pop();
      const name = parts.join('/');

      return {
        fileName,
        details: {
          // This structure and fields are required internally in `patch-package` code.
          version: versionRange,
          name,
          pathSpecifier: name,
          humanReadablePathSpecifier: name,
          packageNames: [name],
        },
      };
    })
  };
}
Example #9
Source File: slitherClient.ts    From remix-project with MIT License 6 votes vote down vote up
mapNpmDepsDir (list) {
    const remixNpmDepsPath = utils.absolutePath('.deps/npm', this.currentSharedFolder)
    const localNpmDepsPath = utils.absolutePath('node_modules', this.currentSharedFolder)
    const npmDepsExists = existsSync(remixNpmDepsPath)
    const nodeModulesExists = existsSync(localNpmDepsPath)
    let isLocalDep = false
    let isRemixDep = false
    let allowPathString = ''
    let remapString = ''

    for (const e of list) {
      const importPath = e.replace(/import ['"]/g, '').trim()
      const packageName = importPath.split('/')[0]
      if (nodeModulesExists && readdirSync(localNpmDepsPath).includes(packageName)) {
        isLocalDep = true
        remapString += `${packageName}=./node_modules/${packageName} `
      } else if (npmDepsExists && readdirSync(remixNpmDepsPath).includes(packageName)) {
        isRemixDep = true
        remapString += `${packageName}=./.deps/npm/${packageName} `
      }
    }
    if (isLocalDep) allowPathString += './node_modules,'
    if (isRemixDep) allowPathString += './.deps/npm,'

    return { remapString, allowPathString }
  }
Example #10
Source File: ProgramsInteract.test.ts    From gear-js with GNU General Public License v3.0 6 votes vote down vote up
testFiles: {
  title: string;
  skip: boolean;
  program: {
    name: string;
    id: number;
    gasLimit: number;
    value: number;
    salt: `0x${string}`;
    account: string;
    meta: boolean;
    initPayload: any;
    log: boolean;
    asU8a: boolean;
  };
  messages: {
    id: number;
    program: number;
    account: string;
    payload: any;
    gasLimit: number;
    asHex: boolean;
    value: number;
    log: string;
  }[];
  mailbox: { message: number; claim: boolean; account: string }[];
}[] = readdirSync('test/spec/programs').map((filePath: string) =>
  yaml.load(readFileSync(join('./test/spec/programs', filePath), 'utf8')),
)
Example #11
Source File: project.ts    From cli with Apache License 2.0 6 votes vote down vote up
private formatResourceFiles(dirPath = this.resourcePath) {
    const files = readdirSync(dirPath, {withFileTypes: true});
    files.forEach((file) => {
      const filePath = join(dirPath, file.name);
      if (file.isDirectory()) {
        this.formatResourceFiles(filePath);
        return;
      }
      if (file.isFile() && extname(filePath) === '.json') {
        const content = readJsonSync(filePath);
        writeJsonSync(filePath, content, Project.jsonFormat);
      }
    });
  }
Example #12
Source File: publish.ts    From icepkg with MIT License 6 votes vote down vote up
function getPackagesPaths(dir) {
  const packagesPaths: string[] = readdirSync(dir).map((dirname) => {
    return join(dir, dirname);
  }).filter((dirpath) => {
    return existsSync(join(dirpath, 'package.json'));
  });

  return packagesPaths;
}
Example #13
Source File: NodeFilesGenerator.ts    From nodemaker with MIT License 6 votes vote down vote up
/**Verify if the two to four files that are to be generated by `generateNodeFuncFiles` were actually generated.*/
  private verifyGeneratedFuncFiles() {
    let files = readdirSync(join("output"));

    const wasGenerated = (snippet: string) =>
      files.some((file) => file.endsWith(snippet));

    const filesToBeVerified = [".node.ts", "GenericFunctions.ts"];

    if (this.nodeGenerationType === NodeGenerationEnum.Complex)
      filesToBeVerified.push("Description.ts");

    if (this.metaParameters.authType === AuthEnum.OAuth2)
      filesToBeVerified.push("OAuth2Api.credentials.ts");

    filesToBeVerified.forEach((file) => {
      if (!wasGenerated(file)) {
        throw Error("Generation failed for file: " + file);
      }
    });
  }
Example #14
Source File: index.ts    From cli with MIT License 6 votes vote down vote up
simpleGenerator = async (
  archivesPath: string,
  yamlData: any,
  extra?: any,
  baseDir?: string
) => {
  if (!baseDir) {
    baseDir = findBaseDir(archivesPath);
  }
  const archivePaths = readdirSync(archivesPath);
  return generator({
    yamlData,
    archivePaths,
    archiveDirPath: './archives/',
    extra,
    baseDir,
  });
}
Example #15
Source File: files.ts    From the-fake-backend with ISC License 6 votes vote down vote up
/**
 * Find the file path of a given dirname and basename.
 *
 * @param dir The file dirname
 * @param base The file basename
 * @param scenario An optional custom scenario for a fixture file
 * @return File path if found
 */
export function findFilePathByDirnameAndBasename(
  dir: string,
  base: string,
  scenario?: string
): string {
  const fullBasename = scenario ? `${base}--${scenario}` : base;

  const [fixture] = readdirSync(dir, { withFileTypes: true })
    .filter(direntIsFile)
    .filter((dirent) => direntFilenameMatchText(fullBasename, dirent));

  if (!fixture) {
    throw new Error('Fixture not found');
  }

  return join(dir, fixture.name);
}
Example #16
Source File: routes.ts    From advanced-node with GNU General Public License v3.0 6 votes vote down vote up
setupRoutes = (app: Express): void => {
  const router = Router()
  readdirSync(join(__dirname, '../routes'))
    .filter(file => !file.endsWith('.map'))
    .map(async file => {
      (await import(`../routes/${file}`)).default(router)
    })
  app.use('/api', router)
}
Example #17
Source File: copy-eslint-config.ts    From s-libs with MIT License 6 votes vote down vote up
export function copyEslintConfig() {
  const targetFolder = 'dist/eslint-config-ng';
  rmdirSync(targetFolder, { recursive: true });
  mkdirSync(targetFolder);

  const srcFolder = 'projects/eslint-config-ng';
  for (const file of readdirSync(srcFolder)) {
    copyFileSync(join(srcFolder, file), join(targetFolder, file));
  }
}
Example #18
Source File: upload-statics.ts    From blog with GNU General Public License v3.0 6 votes vote down vote up
getAllFiles = (path: string): string[] => {
    return readdirSync(path, {
        withFileTypes: true,
        encoding: 'utf8'
    }).reduce((prev: string[], current: Dirent): string[] => {
        if (current.isFile()) {
            return [...prev, join(path, current.name)];
        } else if (current.isDirectory()) {
            return [
                ...prev,
                ...getAllFiles(join(path, current.name))
            ]
        }
    }, []);
}
Example #19
Source File: index.ts    From electron-playground with MIT License 6 votes vote down vote up
function addDevToolsExtension(id: string) {
  if(!EXTENSION_FOLDER) return
  const extensionPath = path.resolve(EXTENSION_FOLDER, id)

  if (!existsSync(extensionPath)) {
    return
  }

  const versionName = readdirSync(extensionPath).find(
    v => existsSync(path.resolve(extensionPath, v)) && /\d+\.\d+\.\d/.test(v),
  )

  if (versionName) {
    session.defaultSession.loadExtension(path.resolve(extensionPath, versionName))
  }
}
Example #20
Source File: index.ts    From sendight-backend with GNU General Public License v3.0 6 votes vote down vote up
readdirSync(__dirname)
  .filter(file => {
    return file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js';
  })
  .forEach(file => {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const model = require(join(__dirname, file))(sequelize, DataTypes);
    db[model.name] = model;
  });
Example #21
Source File: code-size.ts    From protobuf-ts with Apache License 2.0 6 votes vote down vote up
testees: Testee[] = readdirSync(testeesPath, {withFileTypes: true})
    .filter(dirent => dirent.isDirectory())
    .filter(dirent => !exclude.includes(dirent.name))
    .map(dirent => {
        const pluginName = dirent.name.split(".")[0];
        return {
            id: dirent.name,
            pluginName,
            pluginPackage: pluginNameToPackageName(pluginName),
            pluginVersion: pluginNameToVersion(pluginName),
            pluginParameter: readFileSync(join(testeesPath, dirent.name, ".plugin-out/parameters.txt"), "utf-8").trim(),
            webpackFileSize: statSync(join(testeesPath, dirent.name, ".webpack-out/index.js")).size,
            webpackLog: readFileSync(join(testeesPath, dirent.name, ".webpack-out/webpack.log"), "utf-8").trim()
        };
    })
    .sort((a, b) => a.webpackFileSize - b.webpackFileSize)
Example #22
Source File: ReaddirRecursive.ts    From yumeko with GNU Affero General Public License v3.0 6 votes vote down vote up
export default function readdirRecursive(directory: string): string[] {
    const results: string[] = [];

    function read(path: string): void {
        const files = readdirSync(path);

        for (const file of files){
            const dir = join(path, file);
            if (statSync(dir).isDirectory()) read(dir);
            else results.push(dir);
        }
    }
    read(directory);

    return results;
}
Example #23
Source File: semantic-model-provider.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
// Load the library files from the file system.
// To save the libraries to the file system use downloadLibraries.
function loadLibraries(version: TestModelVersion): Record<string, Json> {
  const inputFolder = getModelFolder(version);
  const files = readdirSync(inputFolder);
  const LIBFILE_SUFFIX = ".designtime.api.json";
  const libFiles = filter(files, (_) => _.endsWith(LIBFILE_SUFFIX));
  const libToFileContent = reduce(
    libFiles,
    (libToFileContentMap, file) => {
      const libName = file.substring(0, file.length - LIBFILE_SUFFIX.length);
      libToFileContentMap[libName] = readJsonSync(resolve(inputFolder, file));
      return libToFileContentMap;
    },
    Object.create(null)
  );
  return libToFileContent;
}
Example #24
Source File: init.ts    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
function collectGenerators(generatorsDir: string, genFileName: string = GENERATOR_FILE_NAME): GeneratorInfo[] {
  const dirs = readdirSync(generatorsDir);
  return sortGenerators(dirs.reduce((generators: GeneratorInfo[], name: string) => {
    const generatorPath = path.join(generatorsDir, name);
    if (existsSync(path.join(generatorPath, genFileName)) && statSync(generatorPath).isDirectory()) {
      const generatorExports: GeneratorExports = require(generatorPath);
      if (generatorExports.generator == null) {
        return generators;
      }
      const options = generatorExports.options;
      const params = generatorExports.params;
      const description = generatorExports.description;
      const index = generatorExports.index ?? dirs.length; // will be pushed to a tail if no index

      const iconPath = generatorExports.icon
        ? path.relative(process.cwd(), path.join(generatorPath, generatorExports.icon))
        : undefined;

      generators.push({name, options, params, description, iconPath, index, path: generatorPath});
      return generators;
    } else {
      return generators;
    }
  }, []));
}
Example #25
Source File: LanguageManager.ts    From Asena with MIT License 6 votes vote down vote up
init(){
        const files = readdirSync(LanguageManager.LOCALE_PATH)
        if(!files.length) this.client.logger.error('Language files not found.')

        for(const file of files){
            if(!file.endsWith('.json')){
                this.client.logger.warning(`The language file named ${file} does not end with the '.json' file extension.`)
                continue
            }

            const language = require(`${LanguageManager.LOCALE_PATH}${sep}${file}`)
            this.client.logger.info(`Language loaded: ${Colors.LIGHT_PURPLE + language.full}`)

            const locale = new Language(language)
            LanguageManager.addLanguage(locale)

            if(this.client.version.compare(locale.version) === -1){
                if(locale.code === LanguageManager.DEFAULT_LANGUAGE){
                    this.client.logger.warning(`The default language (${LanguageManager.DEFAULT_LANGUAGE}) version is out of date. Please update the language version.`)
                    process.exit(1)
                }else{
                    this.client.logger.warning(`The ${language.full} language version is out of date. Missing keys will be provided from the default language.`)
                }
            }
        }

        if(!LanguageManager.languages.get(LanguageManager.DEFAULT_LANGUAGE)){
            this.client.logger.error(`Default language (${LanguageManager.DEFAULT_LANGUAGE}) could not be loaded.`)
            process.exit(1)
        }

        this.client.logger.info(`Total ${LanguageManager.languages.size} language successfully loaded!`)
    }
Example #26
Source File: config.service.ts    From nest-react with GNU Lesser General Public License v3.0 6 votes vote down vote up
/**
   * Extract the configuration from both the `config` and `secrets` folders.
   * @param configPath Path to the open `configurations` directory
   * @param secretsPath Path to the `secrets` directory
   */
  private getConfigFromVolumes(
    configPath: string,
    secretsPath: string
  ): DotenvParseOutput {
    const configFiles = readdirSync(configPath).filter(
      file => !file.includes('..')
    );
    const secretsFiles = readdirSync(secretsPath).filter(
      file => !file.includes('..')
    );
    const config: DotenvParseOutput = {};
    configFiles.reduce((partialConfig, file) => {
      partialConfig[file] = this.extractConfigFromFile(join(configPath, file));
      return partialConfig;
    }, config);
    secretsFiles.reduce((partialConfig, file) => {
      partialConfig[file] = this.extractConfigFromFile(join(secretsPath, file));
      return partialConfig;
    }, config);
    return config;
  }
Example #27
Source File: generate-example-files.ts    From airnode with MIT License 6 votes vote down vote up
main = async () => {
  const allIntegrationsFolders = readdirSync(join(__dirname, '../integrations'), { withFileTypes: true })
    .filter((integration) => integration.isDirectory())
    .map((integration) => join(__dirname, '../integrations', integration.name));

  for (const folder of allIntegrationsFolders) {
    const createConfig = await import(join(folder, 'create-config.ts'));
    const createSecretes = await import(join(folder, 'create-secrets.ts'));

    await createConfig.default(true);
    await createSecretes.default(true);
  }
}
Example #28
Source File: init.ts    From jmix-frontend with Apache License 2.0 6 votes vote down vote up
function readClientDir(clientsDirPath: string, generatorFileName?: string): GeneratedClientInfo[] {
  return readdirSync(clientsDirPath, {withFileTypes: true})
    .filter(entry => entry.isDirectory())
    // collect clients only from dirs that contains 'info.json' file
    .filter(entry => fs.existsSync(path.join(clientsDirPath, entry.name, INFO_FILE_NAME)))
    .map((dir): GeneratedClientInfo => {
    return readClient(clientsDirPath, dir.name, generatorFileName);
  });
}
Example #29
Source File: check.ts    From a18n with MIT License 6 votes vote down vote up
getExistingLocales = (localeRoot: string): string[] => {
  const files = readdirSync(localeRoot)
  return keepTruthy(
    files.map((fileName) => {
      const [_, name] = /^(.+)\.json$/.exec(fileName) || []
      return name
    }),
  )
}