fs-extra#readJSON TypeScript Examples

The following examples show how to use fs-extra#readJSON. 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 desktop with MIT License 7 votes vote down vote up
export async function hasGatsbyInstalled(root: string): Promise<boolean> {
  try {
    const packageJson = await readJSON(
      path.join(root, `node_modules`, `gatsby`, `package.json`)
    )
    return packageJson?.name === `gatsby`
  } catch (e) {
    console.warn({ e })
    return false
  }
}
Example #2
Source File: executor.ts    From nx-plugins with MIT License 6 votes vote down vote up
async function caretDepsVersion(normalizedOptions: PublishExecutorNormalizedSchema) {
  const pkgJsonPath = joinPathFragments(normalizedOptions.pkgLocation, 'package.json');
  const packageJson = await readJson(pkgJsonPath);
  const projectsNames = await getAllProjectsNames();

  projectsNames.forEach((name) => {
    if (name in (packageJson.peerDependencies || {})) {
      packageJson.peerDependencies[name] = addCaret(packageJson.peerDependencies[name]);
    }
    if (name in (packageJson.dependencies || {})) {
      packageJson.dependencies[name] = addCaret(packageJson.dependencies[name]);
    }
  });

  await writeJson(pkgJsonPath, packageJson, { spaces: 2 });
}
Example #3
Source File: BinCommand.ts    From joplin-blog with MIT License 6 votes vote down vote up
/**
   * 生成类型定义
   */
  async gen(options: { input?: string }) {
    if (!options.input) {
      return
    }
    const i18nFolderPath = path.resolve(options.input)
    const list = await readdir(i18nFolderPath)
    const i18nJsonPathList = list
      .filter((name) => name.endsWith('.json'))
      .map((name) => path.resolve(i18nFolderPath, name))
    const jsonList = await AsyncArray.map(i18nJsonPathList, (filePath) =>
      readJSON(filePath),
    )
    const translateHandler = new TranslateHandler()
    const configList = translateHandler.parse(jsonList)
    const dts = translateHandler.build(configList)
    await writeFile(path.resolve(i18nFolderPath, 'index.d.ts'), dts)
  }
Example #4
Source File: utils.ts    From desktop with MIT License 6 votes vote down vote up
export async function loadPackageJson(root: string): Promise<PackageJson> {
  return readJSON(path.join(root, `package.json`))
}
Example #5
Source File: login.ts    From cli with Apache License 2.0 6 votes vote down vote up
export async function loginWithApiKey(
  apiKey: string,
  orgId: string,
  env: string
) {
  if (!existsSync(getConfigFilePath())) {
    throw 'Missing config file';
  }
  const cfg = await readJSON(getConfigFilePath());
  cfg.accessToken = apiKey;
  cfg.organization = orgId;
  cfg.environment = env;
  cfg.analyticsEnabled = false;
  cfg.anonymous = true;
  await writeJSON(getConfigFilePath(), cfg);
}
Example #6
Source File: update.ts    From malagu with MIT License 6 votes vote down vote up
async function updatePackage(version: string, skipIntallingComponent?: boolean) {
    const packagePath = join(process.cwd(), 'package.json');
    if (existsSync(packagePath)) {
        const projectPkg = await readJSON(packagePath);
        const dependencies = projectPkg.dependencies ?? {};
        const devDependencies = projectPkg.devDependencies ?? {};
        for (const name of Object.keys(dependencies)) {
            if (name.startsWith('@malagu/')) {
                dependencies[name] = version;
            }
        }

        for (const name of Object.keys(devDependencies)) {
            if (name.startsWith('@malagu/')) {
                devDependencies[name] = version;
            }
        }
        await writeJSON(packagePath, projectPkg, { spaces: 2 });
        if (skipIntallingComponent) {
            await getPackager().install();
        }
    }
}
Example #7
Source File: CliProgram.ts    From joplin-utils with MIT License 6 votes vote down vote up
async generate(name: string): Promise<void> {
    const destPath = path.resolve(this.config.basePath, name)
    await copy(
      path.resolve(__dirname, '../templates/joplin-plugin-template'),
      destPath,
    )
    await move(
      path.resolve(destPath, '_.gitignore'),
      path.resolve(destPath, '.gitignore'),
    )
    const pkgPath = path.resolve(destPath, 'package.json')
    await writeJson(
      pkgPath,
      {
        ...(await readJson(pkgPath)),
        name,
      },
      {
        spaces: 2,
      },
    )
  }
Example #8
Source File: CliProgram.ts    From joplin-utils with MIT License 6 votes vote down vote up
async build(isWatch: boolean): Promise<void> {
    const entryPoints = await promise(
      path.resolve(this.config.basePath, 'src/*.ts'),
    )
    await Promise.all([this.buildScripts(entryPoints), this.copyManifest()])
    if (isWatch) {
      await watch(['src/manifest.json', 'src/*.ts'], {
        cwd: this.config.basePath,
      }).on('change', async (filePath) => {
        if (filePath.endsWith('manifest.json')) {
          await this.copyManifest()
          console.info('copy manifest.json')
        } else if (filePath.endsWith('.ts')) {
          await this.buildScript(path.resolve(this.config.basePath, filePath))
          console.info('buildScript: ', filePath)
        }
      })
      return
    }
    const pkgName = (
      await readJson(path.resolve(this.config.basePath, 'package.json'))
    ).name
    await createArchive({
      sourceDir: path.resolve(this.config.basePath, 'dist'),
      destPath: pkgName + '.jpl',
    })
  }
Example #9
Source File: TagUseService.ts    From joplin-utils with MIT License 6 votes vote down vote up
async save(tags: Pick<TagGetRes, 'id' | 'title'>[]) {
    await this.init()
    const db = await readJson(this.configPath)
    const map = await this.getMap()
    tags.forEach((tag) => {
      map.set(tag.id, {
        id: tag.id,
        title: tag.title,
        lastUseTime: Date.now(),
      } as TagUseEntity)
    })
    await writeJson(this.configPath, {
      ...db,
      tagUse: [...map.values()],
    })
  }
Example #10
Source File: Importer.ts    From joplin-utils with MIT License 6 votes vote down vote up
async readConfig(): Promise<ExportConfig> {
    const list = [
      'folderList',
      'noteList',
      'resourceList',
      'tagList',
      'noteTagRelationList',
    ]
    const configPath = path.resolve(this.config.rootPath, 'config')
    const res = await AsyncArray.map(list, async (fileName) => {
      const config = await readJson(
        path.resolve(configPath, fileName + '.json'),
      )
      return [fileName, config]
    })
    return res.reduce((res, [k, v]) => {
      res[k as keyof ExportConfig] = v
      return res
    }, {} as ExportConfig)
  }
Example #11
Source File: executor.ts    From nx-plugins with MIT License 6 votes vote down vote up
async function syncDepsVersion(normalizedOptions: PublishExecutorNormalizedSchema) {
  const pkgJsonPath = joinPathFragments(normalizedOptions.pkgLocation, 'package.json');
  const packageJson = await readJson(pkgJsonPath);
  const projectsNames = await getAllProjectsNames();
  const version = packageJson.version;

  projectsNames.forEach((name) => {
    if (name in (packageJson.peerDependencies || {})) {
      packageJson.peerDependencies[name] = version;
    }
    if (name in (packageJson.dependencies || {})) {
      packageJson.dependencies[name] = version;
    }
  });

  await writeJson(pkgJsonPath, packageJson, { spaces: 2 });
}
Example #12
Source File: WikiCommander.ts    From joplin-blog with MIT License 6 votes vote down vote up
async checkConfig(): Promise<JoplinBlogConfig | false> {
    const configPath = path.resolve('.joplin-blog.json')
    if (!(await pathExists(configPath))) {
      console.error(
        i18n.t("wiki.Can't find configuration file _joplin-blog_json"),
      )
      return false
    }
    return (await readJson(configPath)) as JoplinBlogConfig
  }
Example #13
Source File: ui5-model.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
async function readFromCache(filePath: string | undefined): Promise<unknown> {
  if (filePath !== undefined) {
    try {
      if ((await pathExists(filePath)) && (await lstat(filePath)).isFile()) {
        return await readJson(filePath);
      }
    } catch (err) {
      getLogger().warn("Could not read cache file For UI5 lib", {
        filePath,
        error: err,
      });
    }
  }
  return undefined;
}
Example #14
Source File: BlogCommander.ts    From joplin-blog with MIT License 6 votes vote down vote up
async checkConfig(): Promise<JoplinBlogConfig | false> {
    const configPath = path.resolve('.joplin-blog.json')
    if (!(await pathExists(configPath))) {
      console.error(
        i18n.t("blog.Can't find configuration file _joplin-blog_json"),
      )
      return false
    }
    return (await readJson(configPath)) as JoplinBlogConfig
  }
Example #15
Source File: nx.ts    From nx-dotnet with MIT License 6 votes vote down vote up
export async function readDependenciesFromNxDepGraph(
  workspaceRoot: string,
  project: string,
) {
  const depGraphFile = join('tmp', 'dep-graph.json');
  execSync(`npx nx dep-graph --file ${depGraphFile}`, {
    cwd: workspaceRoot,
    stdio: 'inherit',
  });
  const absolutePath = join(workspaceRoot, depGraphFile);
  const { graph } = await readJson(absolutePath);
  await remove(absolutePath);

  const deps: Array<{ source: string; target: string }> =
    graph.dependencies[project];
  console.log('[E2E]: Found dependencies', deps);
  return new Set(deps.map((x) => x.target));
}
Example #16
Source File: semantic-model-provider.ts    From ui5-language-assistant with Apache License 2.0 6 votes vote down vote up
export async function readTestLibraryFile(
  version: string,
  fileName: string
): Promise<FetchResponse> {
  try {
    // version might not actually be a TestModelVersion but we'll return ok === false in that case
    // since the file won't exist
    const inputFolder = getModelFolder(version as TestModelVersion);
    const filePath = resolve(inputFolder, fileName);
    const ok = existsSync(filePath);
    return {
      ok: ok,
      json: (): Promise<unknown> => readJson(filePath),
    };
  } catch (error) {
    return {
      ok: false,
      json: (): never => {
        throw error;
      },
    };
  }
}
Example #17
Source File: convert.test.ts    From joplin-utils with MIT License 6 votes vote down vote up
async function migrate2To3(dirs: string[]) {
  await AsyncArray.forEach(dirs, async (dir) => {
    await AsyncArray.map(await readdir(path.resolve(dir)), async (file) => {
      const jsonPath = path.resolve(dir, file as string)
      await writeJson(jsonPath, flatObject(await readJson(jsonPath)), {
        spaces: 2,
      })
    })
  })
  await new GeneratorCommandProgram().main({
    dirs,
    language: 'en',
    watch: false,
  })
}
Example #18
Source File: DownloadedUpdateHelper.ts    From electron-differential-updater with MIT License 5 votes vote down vote up
/**
   * Returns "update-info.json" which is created in the update cache directory's "pending" subfolder after the first update is downloaded.  If the update file does not exist then the cache is cleared and recreated.  If the update file exists then its properties are validated.
   * @param fileInfo
   * @param logger
   */
  private async getValidCachedUpdateFile(fileInfo: ResolvedUpdateFileInfo, logger: Logger): Promise<string | null> {
    const updateInfoFilePath: string = this.getUpdateInfoFile()

    const doesUpdateInfoFileExist = await pathExistsSync(updateInfoFilePath);
    if(!doesUpdateInfoFileExist) {
      return null;
    }


    let cachedInfo: CachedUpdateInfo
    try {
      cachedInfo = await readJson(updateInfoFilePath)
    }
    catch (error) {
      let message = `No cached update info available`
      if (error.code !== "ENOENT") {
        await this.cleanCacheDirForPendingUpdate()
        message += ` (error on read: ${error.message})`
      }
      logger.info(message)
      return null
    }

    const isCachedInfoFileNameValid = cachedInfo?.fileName !== null ?? false
    if (!isCachedInfoFileNameValid) {
      logger.warn(`Cached update info is corrupted: no fileName, directory for cached update will be cleaned`)
      await this.cleanCacheDirForPendingUpdate()
      return null
    }

    if (fileInfo.info.sha512 !== cachedInfo.sha512) {
      logger.info(`Cached update sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${cachedInfo.sha512}, expected: ${fileInfo.info.sha512}. Directory for cached update will be cleaned`)
      await this.cleanCacheDirForPendingUpdate()
      return null
    }

    const updateFile = path.join(this.cacheDirForPendingUpdate, cachedInfo.fileName)
    if (!(await pathExists(updateFile))) {
      logger.info("Cached update file doesn't exist, directory for cached update will be cleaned")
      await this.cleanCacheDirForPendingUpdate()
      return null
    }

    const sha512 = await hashFile(updateFile)
    if (fileInfo.info.sha512 !== sha512) {
      logger.warn(`Sha512 checksum doesn't match the latest available update. New update must be downloaded. Cached: ${sha512}, expected: ${fileInfo.info.sha512}`)
      await this.cleanCacheDirForPendingUpdate()
      return null
    }
    this._downloadedFileInfo = cachedInfo
    return updateFile
  }
Example #19
Source File: package-info.ts    From algo-builder with Apache License 2.0 5 votes vote down vote up
export async function getPackageJson(): Promise<PackageJson> {
	const root = getPackageRoot();
	return await readJSON(path.join(root, "package.json"));
}
Example #20
Source File: executor.ts    From nx-plugins with MIT License 5 votes vote down vote up
async function getAllProjectsNames() {
  const tsconfig = await readJson('tsconfig.base.json');
  const paths = tsconfig.compilerOptions.paths;
  return Object.keys(paths);
}
Example #21
Source File: launcher.ts    From desktop with MIT License 5 votes vote down vote up
async function getPackageJson(root: string): Promise<PackageJsonWithBin> {
  return readJSON(`${root}/node_modules/gatsby/package.json`)
}
Example #22
Source File: login.ts    From cli with Apache License 2.0 5 votes vote down vote up
export async function clearAccessTokenFromConfig() {
  if (!existsSync(getConfigFilePath())) {
    return;
  }
  const cfg = await readJSON(getConfigFilePath());
  delete cfg.accessToken;
  await writeJSON(getConfigFilePath(), cfg);
}
Example #23
Source File: login.ts    From cli with Apache License 2.0 5 votes vote down vote up
export async function isLoggedin() {
  if (!existsSync(getConfigFilePath())) {
    return false;
  }
  const cfg = await readJSON(getConfigFilePath());
  return Boolean(cfg.accessToken);
}
Example #24
Source File: npm.ts    From malagu with MIT License 5 votes vote down vote up
readLockfile(lockfilePath: string) {
        return readJSON(lockfilePath);
    }
Example #25
Source File: init-manager.ts    From malagu with MIT License 5 votes vote down vote up
async render(): Promise<void> {
        const packageJsonPath = resolve(this.outputDir, 'package.json');
        if (existsSync(packageJsonPath)) {
            const packageJson = await readJSON(packageJsonPath, { encoding: 'utf8' });
            packageJson.name = basename(this.outputDir);
            await writeJSON(packageJsonPath, packageJson, { encoding: 'utf8', spaces: 2 });
        }
    }
Example #26
Source File: index.ts    From yarn-plugins with MIT License 5 votes vote down vote up
function readTsConfig(ws: TestWorkspace): Promise<unknown> {
  return readJSON(getTsConfigPath(ws));
}
Example #27
Source File: npm.ts    From DefinitelyTyped-tools with MIT License 5 votes vote down vote up
export async function withNpmCache<T>(
  uncachedClient: UncachedNpmInfoClient,
  cb: (client: CachedNpmInfoClient) => Promise<T>,
  cacheDir = defaultCacheDir
): Promise<T> {
  const log = loggerWithErrors()[0];
  const cacheFile = joinPaths(cacheDir, cacheFileBasename);
  let unroll: Map<string, NpmInfo>;
  log.info(`Checking for cache file at ${cacheFile}...`);
  const cacheFileExists = await pathExists(cacheFile);
  if (cacheFileExists) {
    log.info("Reading cache file...");
    const cachedJson = (await readJson(cacheFile)) as Record<string, NpmInfoRaw>;
    log.info(`Cache file ${cacheFile} exists, copying to map...`);
    unroll = recordToMap(cachedJson, npmInfoFromJson);
  } else {
    log.info("Cache file doesn't exist, using empty map.");
    unroll = new Map();
  }

  const res = await cb({ getNpmInfoFromCache, fetchAndCacheNpmInfo });
  log.info("Writing npm cache.");
  await ensureFile(cacheFile);
  await writeJson(cacheFile, mapToRecord(unroll, jsonFromNpmInfo));
  return res;

  /** May return old info -- caller should check that this looks up-to-date. */
  function getNpmInfoFromCache(escapedPackageName: string): NpmInfo | undefined {
    return unroll.get(escapedPackageName);
  }

  /** Call this when the result of getNpmInfoFromCache looks potentially out-of-date. */
  async function fetchAndCacheNpmInfo(escapedPackageName: string): Promise<NpmInfo | undefined> {
    const info = await uncachedClient.fetchNpmInfo(escapedPackageName);
    if (info) {
      unroll.set(escapedPackageName, info);
    }
    return info;
  }
}
Example #28
Source File: TagUseService.ts    From joplin-utils with MIT License 5 votes vote down vote up
async getMap(): Promise<Map<string, TagUseEntity>> {
    await this.init()
    const list: TagUseEntity[] = (await readJson(this.configPath)).tagUse
    return list.reduce(
      (res, item) => res.set(item.id, item),
      new Map<string, TagUseEntity>(),
    )
  }
Example #29
Source File: WikiCommander.ts    From joplin-utils with MIT License 5 votes vote down vote up
async checkConfig(): Promise<JoplinBlogConfig | false> {
    const configPath = path.resolve('.joplin-blog.json')
    if (!(await pathExists(configPath))) {
      console.error(i18n.t('common.notFoundConfig'))
      return false
    }
    return (await readJson(configPath)) as JoplinBlogConfig
  }