当前位置: 首页>>代码示例>>TypeScript>>正文


TypeScript fs-extra.readJSON函数代码示例

本文整理汇总了TypeScript中fs-extra.readJSON函数的典型用法代码示例。如果您正苦于以下问题:TypeScript readJSON函数的具体用法?TypeScript readJSON怎么用?TypeScript readJSON使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了readJSON函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的TypeScript代码示例。

示例1: async

 const migrateV6Plugins = async () => {
   if (!await fs.pathExists(pluginsDir)) return
   process.stderr.write('heroku: migrating plugins\n')
   try {
     const p = path.join(pluginsDir, 'user.json')
     if (await fs.pathExists(p)) {
       const {manifest} = await fs.readJSON(p)
       for (let plugin of Object.keys(manifest.plugins)) {
         process.stderr.write(`heroku-cli: migrating ${plugin}\n`)
         await exec('heroku', ['plugins:install', plugin])
       }
     }
   } catch (err) {
     this.warn(err)
   }
   try {
     const p = path.join(pluginsDir, 'link.json')
     if (await fs.pathExists(p)) {
       const {manifest} = await fs.readJSON(path.join(pluginsDir, 'link.json'))
       for (let {root} of Object.values(manifest.plugins) as any) {
         process.stderr.write(`heroku-cli: migrating ${root}\n`)
         await exec('heroku', ['plugins:link', root])
       }
     }
   } catch (err) {
     this.warn(err)
   }
   await fs.remove(pluginsDir)
   process.stderr.write('heroku: done migrating plugins\n')
 }
开发者ID:jimmyurl,项目名称:cli,代码行数:30,代码来源:plugin-migrate.ts

示例2: writeTestingPackageJson

/**
 * For a given repo, generate a new package.json and write it to disk. This
 * is a testing-specific package.json manifest, which means that it will
 * include local references to dependencies that were also converted in the
 * workspace.
 */
async function writeTestingPackageJson(
    repo: WorkspaceRepo,
    localConversionMap: Map<string, string>,
    options: WorkspaceTestSettings) {
  const bowerPackageName = path.basename(repo.dir);
  const bowerJsonPath = path.join(repo.dir, 'bower.json');
  const bowerJson = await fse.readJSON(bowerJsonPath);
  const npmPackageName =
      lookupNpmPackageName(bowerJsonPath) || bowerPackageName;

  const packageJsonPath = path.join(repo.dir, 'package.json');
  const existingPackageJson =
      await readJsonIfExists<Partial<YarnConfig>>(packageJsonPath);

  const packageJson = generatePackageJson(
      bowerJson,
      {
        name: npmPackageName,
        version: options.packageVersion,
        flat: options.flat,
        private: options.private,
      },
      localConversionMap,
      existingPackageJson);
  writeJson(packageJson, packageJsonPath);
}
开发者ID:,项目名称:,代码行数:32,代码来源:

示例3:

export async function readJsonIfExists<T>(filepath: string):
    Promise<T|undefined> {
  if (await fse.pathExists(filepath)) {
    return await fse.readJSON(filepath) as T;
  }
  return undefined;
}
开发者ID:,项目名称:,代码行数:7,代码来源:

示例4: initializeFromJsonFile

export async function initializeFromJsonFile(jsonFilepath: string, debug?: boolean): Promise<void> {
    if (!await fse.pathExists(jsonFilepath)) {
        throw new Error(`The Json file '${jsonFilepath}' does not exist.`);
    }

    const { publisher, name, version, aiKey } = await fse.readJSON(jsonFilepath);
    initialize(`${publisher}.${name}`, version, aiKey, !!debug);
}
开发者ID:Manu-sh,项目名称:dotfiles,代码行数:8,代码来源:index.ts

示例5: initilizeFromJsonFile

 export async function initilizeFromJsonFile(fsPath: string): Promise<void> {
     if (await fse.pathExists(fsPath)) {
         const { publisher, name, version, aiKey } = await fse.readJSON(fsPath);
         initilize(publisher, name, version, aiKey);
     } else {
         throw new Error(`The Json file '${fsPath}' does not exist.`);
     }
 }
开发者ID:Manu-sh,项目名称:dotfiles,代码行数:8,代码来源:TelemetryWrapper.ts

示例6: prepareHTML

export function prepareHTML(param: IPrepareHTMLOptions): Promise<string> {
    const filter = moveTo(param.target);

    return Promise.all([
        readFile(join(__dirname, '../src/index.html'), 'utf8'),
        readJSON(join(__dirname, '../package.json')),
        readJSON(join(__dirname, './meta.json'))
    ])
        .then((data) => {
            const [file, pack, meta] = data;
            const connectionTypes = ['mainnet', 'testnet'];

            if (!param.scripts) {
                const sourceFiles = getFilesFrom(join(__dirname, '../src'), '.js', function (name, path) {
                    return !name.includes('.spec') && !path.includes('/test/');
                });
                param.scripts = meta.vendors.map((i) => join(__dirname, '..', i)).concat(sourceFiles);
                param.scripts.push(join(__dirname, '../loginDaemon.js'));
            }

            if (!param.styles) {
                param.styles = meta.stylesheets.map((i) => join(__dirname, '..', i)).concat(getFilesFrom(join(__dirname, '../src'), '.less'));
            }

            const networks = connectionTypes.reduce((result, item) => {
                result[item] = meta.configurations[item];
                return result;
            }, Object.create(null));

            return compile(file)({
                pack: pack,
                domain: meta.domain,
                build: {
                    type: 'web'
                },
                network: networks[param.connection]
            });
        })
        .then((file) => {
            return replaceStyles(file, param.styles.map(filter).map(s => `/${s}`));
        }).then((file) => {
            return replaceScripts(file, param.scripts.map(filter));
        });
}
开发者ID:beregovoy68,项目名称:WavesGUI,代码行数:44,代码来源:utils.ts

示例7: async

      read: async () => {
        const [data, stat] = await Promise.all([fs.readJSON(filepath), fs.stat(filepath)]);

        // Throw an error instead of returning stale data if the file has expired
        if (Date.now() - stat.mtimeMs > expiryInMin * 60 * 1000) {
          throw new CacheExpiredError('Cache expired', filepath, stat.mtimeMs);
        }

        return data;
      },
开发者ID:nusmodifications,项目名称:nusmods,代码行数:10,代码来源:io.ts

示例8: fetchCache

export async function fetchCache(cachePath: string, cacheDuration: number, options: any): Promise<Array<string>> {
  let cachePresent = fs.existsSync(cachePath)
  if (cachePresent && !_isStale(cachePath, cacheDuration)) {
    return fs.readJSON(cachePath)
  }
  const cache = await options.cacheFn()
  // TODO: move this to a fork
  await updateCache(cachePath, cache)
  return cache
}
开发者ID:heroku,项目名称:cli,代码行数:10,代码来源:cache.ts

示例9: getBuildParams

export async function getBuildParams(param: IPrepareHTMLOptions) {
    const [pack, meta, themesConf] = await Promise.all([
        readJSON(join(__dirname, '../package.json')) as Promise<IPackageJSON>,
        readJSON(join(__dirname, './meta.json')) as Promise<IMetaJSON>,
        readJSON(join(__dirname, '../src/themeConfig/theme.json'))
    ]);

    const { themes } = themesConf;
    const { domain, analyticsIframe } = meta as any;
    const { connection, type, buildType, outerScripts = [] } = param;
    const config = meta.configurations[connection];

    const networks = ['mainnet', 'testnet'].reduce((result, connection) => {
        result[connection] = meta.configurations[connection];
        return result;
    }, Object.create(null));

    const scripts = getScripts(param, pack, meta).concat(outerScripts);
    const styles = getStyles(param, meta, themes);
    const isWeb = type === 'web';
    const isProduction = buildType && buildType === 'min';
    const matcherPriorityList = connection === 'mainnet' ? MAINNET_DATA : TESTNET_DATA;
    const { origin, oracle, feeConfigUrl, bankRecipient } = config;

    return {
        pack,
        isWeb,
        origin,
        analyticsIframe,
        oracle,
        domain,
        styles,
        scripts,
        isProduction,
        feeConfigUrl,
        bankRecipient,
        build: { type },
        matcherPriorityList,
        network: networks[connection],
        themesConf: themesConf,
        langList: meta.langList,
    };
}
开发者ID:wavesplatform,项目名称:WavesGUI,代码行数:43,代码来源:utils.ts

示例10: Ajv

export function validate<T>(data: T, schemaName: string): Promise<T> {
    const respath = path.join(path.dirname(__dirname), "res");
    return fs.readJSON(path.join(respath, schemaName + ".json")).then(function (schema) {
        const ajv = new Ajv({ schemaId: 'auto', allErrors: true });
        const metaschema = require('ajv/lib/refs/json-schema-draft-04.json');
        ajv.addMetaSchema(metaschema);
        if (!ajv.validate(schema, data)) {
            throw ("JSON schema errors: " + JSON.stringify(ajv.errors, null, 2));
        }
        return data;
    })
}
开发者ID:crepi22,项目名称:dccjs,代码行数:12,代码来源:constants.ts

示例11: get_railroad

/** get_railroad loads the current railroad from the resources. */
function get_railroad(): Promise<IRailRoadImplem> {
    const filePath = path.join(RES_FOLDER, "railroad.json");
    return (fs.readJSON(filePath, { encoding: "UTF-8" }) as Promise<IRailRoadImplem>).then(
        data => validate(data, "IRailRoad").then(function(data) {
            for(let i=0; i< data.occupancy.length; i++) {
                data.occupancy[i].id = i;
            }
            return data;
        })
    ).catch(
        err => (console.log("Cannot proceed without railroad description file: " + err), process.exit(1)));
}
开发者ID:crepi22,项目名称:dccjs,代码行数:13,代码来源:constants.ts

示例12: async

 return async (...args: any[]): Promise<any> => {
   let f = path.join(cacheDir, `${key}.json`)
   try {
     let fi = await fs.stat(f)
     if (fi && minutesAgo(20) < fi.mtime) {
       return await fs.readJSON(f)
     }
   } catch (err) {
     debug(err)
     submitError(err)
     await fs.remove(f)
   }
   let body = await fn(...args)
   await fs.outputJSON(f, body)
   return body
 }
开发者ID:dickeyxxx,项目名称:tmux-weather,代码行数:16,代码来源:tmux-weather.ts

示例13: read

  /**
   * parse manifest
   * @returns {Promise<void>}
   */
  async read() {
    const zip = new Node7z()
    await zip.extractFull(this.filename, this.tempDir)
    const manifestFile = path.join(this.tempDir, 'modpack.json')
    if (!await fs.pathExists(manifestFile)) {
      throw new Error('invalid modpack: modpack.json not found')
    }
    const manifest = await fs.readJSON(manifestFile)
    const validatorResult = validate(manifest, ModpackManifestSchema)
    if (!validatorResult.valid) {
      let err = new Error('invalid modpack: modpack.json format error')
      err['validate'] = validatorResult.errors
      throw err
    }

    this.manifest = manifest
  }
开发者ID:bangbang93,项目名称:BMCLJS,代码行数:21,代码来源:modpack.ts

示例14: read_locomotive

/** Reads a locomotive description file 
 * @param locoPath path to a folder containing a locomotive description.
 * @return a promise of locomotive description object.
 */
function read_locomotive(locoPath: string): Promise<ILocomotive> {
    const locoFile = path.join(locoPath, "loco.json");
    return (fs.readJSON(locoFile, { encoding: "UTF-8" }) as Promise<ILocomotive>).then(
        data => validate(data, "ILocomotive")
    ).then (
        function (loco) {
            
            const locoImgFile = path.join(locoPath, "image.jpg");
            if (loco.image) { return loco; }
            return fs.pathExists(locoImgFile).then(
                function (existsImage) {
                    console.log(locoImgFile + " => " + existsImage);
                    if (existsImage) {
                        loco.image = locoImgFile;
                    } else {
                        loco.image = path.join(path.dirname(__dirname), "res/loco.jpg");
                    }
                    return loco;
                });
        }).catch(
            function (err) { throw ("(" + locoPath + "): " + err); }
        );
}
开发者ID:crepi22,项目名称:dccjs,代码行数:27,代码来源:constants.ts

示例15: convert

/**
 * Convert a package-layout project to JavaScript modules & npm.
 */
export default async function convert(options: PackageConversionSettings) {
  const outDir = options.outDir;
  const npmPackageName = options.packageName;
  await setupOutDir(outDir, options.cleanOutDir);

  // Configure the analyzer and run an analysis of the package.
  const bowerJson =
      await fse.readJSON(path.join(options.inDir, 'bower.json')) as
      Partial<BowerConfig>;
  const bowerPackageName = bowerJson.name!;
  const analyzer = configureAnalyzer(options);
  const analysis = await analyzer.analyzePackage();
  await setupOutDir(options.outDir, !!options.cleanOutDir);

  // Create the url handler & converter.
  const urlHandler = new PackageUrlHandler(
      analyzer,
      bowerPackageName,
      npmPackageName,
      options.packageType,
      options.inDir);
  const conversionSettings = createDefaultConversionSettings(analysis, options);
  const converter =
      new ProjectConverter(analysis, urlHandler, conversionSettings);

  // Convert the package
  await converter.convertPackage(bowerPackageName);

  // Filter out external results before writing them to disk.
  const results = converter.getResults();
  for (const [newPath] of results) {
    if (!PackageUrlHandler.isUrlInternalToPackage(newPath)) {
      results.delete(newPath);
    }
  }
  await writeFileResults(outDir, results);

  // transform travis config
  await transformTravisConfig(options.inDir, options.outDir);

  // add `node_modules` to gitignore
  const gitIgnoreFile = path.join(options.inDir, '.gitignore');
  await ignoreNodeModules(gitIgnoreFile);

  const packageJsonPath = path.join(options.inDir, 'package.json');
  const existingPackageJson =
      await readJsonIfExists<Partial<YarnConfig>>(packageJsonPath);

  // Generate a new package.json, and write it to disk.
  const packageJson = generatePackageJson(
      bowerJson,
      {
        name: options.packageName,
        version: options.packageVersion,
        flat: options.flat,
        private: options.private,
      },
      undefined,
      existingPackageJson);
  writeJson(packageJson, packageJsonPath);

  // Delete files that were explicitly requested to be deleted.
  if (options.deleteFiles !== undefined) {
    await deleteGlobsSafe(options.deleteFiles, outDir);
  }

  // TODO(fks): create a new manifest.json, and write it to disk.
  // Currently blocked by the fact that package-url-handler treats all
  // dependencies as local/internal.
}
开发者ID:,项目名称:,代码行数:73,代码来源:


注:本文中的fs-extra.readJSON函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。